如何在javascript中划分多个数组

Posted

技术标签:

【中文标题】如何在javascript中划分多个数组【英文标题】:How to divide multi array in javascript 【发布时间】:2021-07-19 06:25:49 【问题描述】:

我有一个数组,每个索引中有 3 个数据 变量

var data = @json($data)

输出

(6) […, …, …, …, …, …]
0: day: "Saturday", totalIncome: 0, totalExpense: 300
1: day: "Sunday", totalIncome: 0, totalExpense: 0
2: day: "Monday", totalIncome: 0, totalExpense: 0
3: day: "Tuesday", totalIncome: 0, totalExpense: 0
4: day: "Wednesday", totalIncome: 500, totalExpense: 0
5: day: "Thursday", totalIncome: 0, totalExpense: 0
length: 6

我想做3个数组

var days = datas.day;
var incomes = datas.totalIncome;
var expenses = data.totalExpenses;

我现在应该怎么做才能从数据中创建这 3 个数组。请帮忙

【问题讨论】:

var data = @json($data) 看起来不像是有效的 JS? 对 laravel php 有效。 php数组到js数组的转换 那么 javascript 标签是干什么用的? ***.com/questions/33326699/… 您可以从中找到答案。谢谢 【参考方案1】:

在原版 JS 中可能是这样的:

const days = [], incomes = [], expenses = [];

for (let i = 0; i < data.length; i++) 
    days.push(data[i]["day"]);
    incomes.push(data[i]["totalIncome"]);
    expenses.push(data[i]["totalExpense"]);

【讨论】:

【参考方案2】:

将您的数据映射到新数组中。

var days = datas.map(function(obj) 
    return obj['day'];
);
var incomes = datas.map(function(obj) 
    return obj['income'];
);
var expenses = datas.map(function(obj) 
    return obj['expenses'];
);

如果您安装了lodash

var days = _.pluck(datas, 'day')

【讨论】:

【参考方案3】:

使用原生的flatMap函数,例如:

    var groupBy = key => 
        return [
           day: "Saturday", totalIncome: 0, totalExpense: 300,
           day: "Sunday", totalIncome: 0, totalExpense: 0,
           day: "Monday", totalIncome: 0, totalExpense: 0,
           day: "Tuesday", totalIncome: 0, totalExpense: 0,
           day: "Wednesday", totalIncome: 500, totalExpense: 0,
           day: "Thursday", totalIncome: 0, totalExpense: 0
        ].flatMap(v => v[key])
    


    const days = groupBy('day')
    console.log(days)

【讨论】:

以上是关于如何在javascript中划分多个数组的主要内容,如果未能解决你的问题,请参考以下文章

Javascript - 计算相同的值并划分数组中相同值的结果

如何在javascript中从多个数组中获取单个数组[重复]

如何在 Javascript 或 Jquery 中处理具有多个循环的大量数组?

java_内存的划分

如何划分一个数组的信息并发送到另一个数组? [复制]

如何用JavaScript替换数组中间隔多个参数