gpt4 book ai didi

JavaScript:根据不同的对象数组编译对象数组

转载 作者:行者123 更新时间:2023-11-28 08:30:49 25 4
gpt4 key购买 nike

我有一个发票数组,我想根据值invoiceMonth(例如“2014年2月”)编译monthlyIncome的有序列表”)。 monthlyIncome 数组必须存储月份名称和该月的收入,即

monthlyIncome = [
{ name: 'January 2014', income: 1000},
{ name: 'February 2014', income: 1500 }
...
];

基本上我需要的是一种“更深”的indexOf(val),它会检查val是否在任何对象的指定属性中MonthlyIncome,然后返回该索引。在此示例中,我使用 deepIndexOf(value, property)

for (var i=0; i<invoices.length; i++) {
var index = monthlyIncome.deepIndexOf(invoices[i].invoiceMonth, 'name');
if (index > -1) {
// month already exists in list, so add the total
monthlyIncome[index].income += invoice.total;
} else {
// month doesn't exist, so add it
monthlyIncome.push({
name: invoices[i].invoiceMonth,
income: invoices[i].total
});
}
}

唯一的问题是我不知道如何编写 deepIndexOf。另外,我怀疑在 JavaScript 中存在比我概述的方法更好的方法。

最佳答案

您的 deepIndexOf 函数可以是这样的:

function deepIndexOf(array, key, value) {
var obj;
for (var idx = 0; idx < array.length; idx++) {
var obj = array[idx];
if (obj[key] === value) {
return idx;
}
}
return -1;
}

var monthlyIncome = [{
name: 'January 2014',
income: 1000
}, {
name: 'February 2014',
income: 1500
}];

console.log(deepIndexOf(monthlyIncome, 'name', 'January 2014'));
console.log(deepIndexOf(monthlyIncome, 'name', 'February 2014'));
console.log(deepIndexOf(monthlyIncome, 'name', 'None 2014'));

或者,要编译的整个代码可以是这样的:

function compile(incomeList, invoice) {
var found = false;
for (var i = 0; i < incomeList.length && !found; i++) {
if (incomeList[i].name === invoice.invoiceMonth) {
incomeList[i].income += invoice.total;
found = true;
}
}
if (!found) {
incomeList.push({
name: invoice.invoiceMonth,
income: invoice.total
});
}

}

compile(monthlyIncome, {
invoiceMonth: 'January 2014',
total: 1000
});
compile(monthlyIncome, {
invoiceMonth: 'March 2014',
total: 1000
});

关于JavaScript:根据不同的对象数组编译对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21887218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com