gpt4 book ai didi

javascript - 迭代对象中的嵌套数组以整理信息

转载 作者:行者123 更新时间:2023-11-29 16:36:48 25 4
gpt4 key购买 nike

我有以下对象数组:

let array = [
{key: 'Newcastle', values[
{key: 'ID1000', values[
{name: 'Jeff', cust_id: "ID1000", status: 'sold'},
{name: 'Jeff', cust_id: "ID1000", status: 'pending'},
]}
{key: 'ID2000', values [
{name: 'Bob', cust_id: "ID2000", status: 'sold'}
]}
]}
{key: 'London', values [
{key: 'ID3000', values[
{name: 'Gary', cust_id: "ID3000", status: 'sold'},
]}
{key: 'ID4000', values[
{name: 'Mary', cust_id: "ID4000", status: 'interest'},
{name: 'Mary', cust_id: "ID4000", status: 'interest'},
{name: 'Mary', cust_id: "ID4000", status: 'pending'},
]}
]}
]

我一直在尝试将其重构为:

[
{Location: 'Newcastle, customers: 2, sold: 2, pending: 1, interest: 0},
{Location: 'London', customers: 2, sold: 1, pending: 1, interest: 2}
]

因此,我尝试计算状态事件的数量并相应地整理它们。

当我尝试迭代嵌套数组,然后尝试将迭代结果冒泡到最终对象时,我迷失了方向。我得到的最接近的是:

function transform(array) {
let arr = []
array.forEach(function(x) {
function soldCount() {
x.values.forEach(function(x) {

let sold = x.values.forEach(function(x) {
let soldTrue = 0
if (x.status === "sold") {
soldTrue++
}
console.log(soldTrue)
if (soldTrue > 0) {
return soldTrue
}
})

})
}
let obj = {
location: x.key,
customers: x.values.length,
sold: soldCount()
}

arr.push(obj)
})
return arr
}

这会尝试迭代对象中的每个数组,并尝试返回一个数字来表示它找到的“已售出”状态数量。控制台语句确实返回一个数字,但由于“forEach”,它为数组中的每个项目返回多个条目。

我陷入了在嵌套数组上迭代的许多 forEach 循环中。我怀疑这可能不是我想要实现的目标的正确方法。

最佳答案

您可以获取一个对象计数状态并构建一个新对象。

var array = [{ key: 'Newcastle', values: [{ key: 'ID1000', values: [{ name: 'Jeff', cust_id: "ID1000", status: 'sold' }, { name: 'Jeff', cust_id: "ID1000", status: 'pending' },] }, { key: 'ID2000', values: [{ name: 'Bob', cust_id: "ID2000", status: 'sold' }] }] }, { key: 'London', values: [{ key: 'ID3000', values: [{ name: 'Gary', cust_id: "ID3000", status: 'sold' },] }, { key: 'ID4000', values: [{ name: 'Mary', cust_id: "ID4000", status: 'interest' }, { name: 'Mary', cust_id: "ID4000", status: 'interest' }, { name: 'Mary', cust_id: "ID4000", status: 'pending' }] }] }],
result = array.map(({ key: Location, values }) => {
var data = { Location, customers: 0, sold: 0, pending: 0, interest: 0 };
values.forEach(({ values }) => {
data.customers++;
values.forEach(({ status }) => data[status]++);
});
return data;
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 迭代对象中的嵌套数组以整理信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50525397/

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