gpt4 book ai didi

javascript - 如何在 JavaScript 中展平嵌套数组?

转载 作者:行者123 更新时间:2023-11-27 22:50:10 26 4
gpt4 key购买 nike

我有带有嵌套数组的复杂数组。例如,如果我想从最后一个数组获取数据,那么我必须编写: partners[0].products[0].campaigns[0].nameCampaign.type.price等等

enter image description here

我想展平这个数组。这就是我所期望的: enter image description here

这可能吗?

<小时/>

@编辑这是 console.log(JSON.stringify(partners, 0, 4)); 的一部分:

[{
"_id": "57727902d0a069e41a34eece",
"namePartner": "Self",
"products": [{
"_id": "57727910d0a069e41a34eed0",
"nameProduct": "Singl",
"campaigns": [{
"_id": "57727937d0a069e41a34eed1",
"type": "lead",
"nameCampaign": "Camp 0"
}]
}, {
"_id": "5774cb68c594b22815643b37",
"nameProduct": "DrugiPartner"
"campaigns": [{
"_id": "5774cb78c594b22815643b38",
"type": "subscription",
"nameCampaign": "DrugaKampania"
}, {
"_id": "5774cbedc594b22815643b3a",
"type": "subscription",
"nameCampaign": "TrzeciaKampania"
}, {
"_id": "5774cbf9c594b22815643b3b",
"type": "subscription",
"nameCampaign": "CzwartaKampania"
}]
}, {
"_id": "5774cbdbc594b22815643b39",
"nameProduct": "Trzeci"
"campaigns": []
}]
}]

最佳答案

在普通的 Javascript 中,您可以使用包含对所需项目和数组的引用的数组,并使用迭代递归方法来获取所需数组。

编辑

要添加多个属性,您可以对多个项目使用数组。

一个属性:

{ use: 'namePartner' }

多个属性:

{ use: ['nameCampains', 'type'] }

function iter(a, r, l) {
if (Array.isArray(a)) {
a.forEach(function (b) {
var use = level[l].use,
rr = JSON.parse(JSON.stringify(r));
(Array.isArray(use) && use || [use]).forEach(function (c) {
rr[c] = b[c];
});
iter(b[level[l].array], rr, l + 1);
});
return;
}
result.push(r);
}

var partners = [{ namePartner: 'Tesco', products: [{ nameProduct: 'New', campains: [{ nameCampains: 'Apple', type: 'appleType' }, { nameCampains: 'Lenovo', type: 'lenovoType' }] }] }, { namePartner: 'Eko', products: [{ nameProduct: 'Fresh', campains: [{ nameCampains: 'Asus', type: 'asusType' }, { nameCampains: 'Dell', type: 'dellType' }] }, { nameProduct: 'new', campains: [{ nameCampains: 'Samsung', type: 'samsungType' }] }] }],
level = [{ use: 'namePartner', array: 'products' }, { use: 'nameProduct', array: 'campains' }, { use: ['nameCampains', 'type'] }],
result = [];

iter(partners, {}, 0);
console.log(result);

关于javascript - 如何在 JavaScript 中展平嵌套数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38120524/

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