gpt4 book ai didi

javascript - 从 JSON 数组的数组属性中提取值

转载 作者:行者123 更新时间:2023-12-01 00:19:25 25 4
gpt4 key购买 nike

我有一个元素数组,每个元素都非常复杂,因为它的属性是包含其他数组作为属性的数组。我想提取这个元素的几个属性,我尝试过使用 forEach 函数,但它不起作用。

数组来自json文件,这就是我使用axios的原因,数组的元素是这样的:

{
"ITEMS":[
{
"id":"0001",
"name":"foo",
"sizes":[
{
"name":"small",
"id":"9999",
"available":"no"
},
{
"name":"medium",
"id":"9998",
"available":"yes"
}
]
},

{
"id":"0002",
"name":"bar",
"sizes":[
{
"name":"small",
"id":"4444",
"available":"yes"
},
{
"name":"medium",
"id":"4443",
"available":"no"
}
]
},
...
]
}

所以我想收集它们的属性,创建被推送到数组中并复制此模型的元素:

this.sample = {
colour:'item.name',
size:'item.size.name[i]',
idcode:'item.id',
sizecode:'item.size.id[i]',
available:'item.size.available[i]'
}

这是我的尝试(不起作用)

const axios = require('axios');
class IndianaJones {
constructor(){
this.sample = {
name:'',
colour:'',
size:'',
idcode:'',
sizecode:'',
available:''
},
this.newids = ["10","11","12"...]
this.freshprods = []
}

async FreshProd(){
for(this.i=0;this.i<this.newids.length;this.i++){
this.prod = await axios.get(`https://blablabla/${this.newids[this.i]}.json`)
this.ITEMS.forEach(function(item){
this.sample.idcode=item.id;
this.sample.colour=item.name;
item.sizes.forEach(function(SIZE){
this.sample.size=SIZE.name
this.sample.sizecode=SIZE.id
this.sample.available=SIZE.available
this.freshprods.push(this.sample)
})
}
)
}
return this.freshprods
}
}

(async()=>{
const indiana = new IndianaJones();
await indiana.FreshProd()
})()

真的,这让我陷入困境,我会非常感谢任何可以帮助我的人,也许 LODASH 会有用?

最佳答案

您正在尝试使结构扁平化。为此,您可以使用Array.flatMap()(或lodash的_.flatMap()来迭代ITEMS,映射尺寸 数组,并为每个大小返回一个新对象:

const prods = {"ITEMS":[{"id":"0001","name":"foo","sizes":[{"name":"small","id":"9999","available":"no"},{"name":"medium","id":"9998","available":"yes"}]},{"id":"0002","name":"bar","sizes":[{"name":"small","id":"4444","available":"yes"},{"name":"medium","id":"4443","available":"no"}]}]};

const freshprods = prods.ITEMS.flatMap(
({ id: idcode, name: colour, sizes }) =>
sizes.map(o => ({
colour,
size: o.name,
idcode,
sizecode: o.id,
available: o.available
}))
);

console.log(freshprods);

关于javascript - 从 JSON 数组的数组属性中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59539469/

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