gpt4 book ai didi

Javascript : Store JSON data in array

转载 作者:行者123 更新时间:2023-11-30 06:20:35 25 4
gpt4 key购买 nike

我有这样的 JSON。

[{
"address": "A-D-1",
"batch": [{
"batch_number": "B-123",
"cost": [{
"cost": "C1"
}]
}]
},
{
"address": "A-85-1",
"batch": [{
"batch_number": "B-6562",
"cost": [{
"cost": "C16464"
}]
}]
},
{
"address": "A-522-1",
"batch": [{
"batch_number": "B-4511",
"cost": [{
"cost": "C8745"
}]
}]
}]

我想将我的 JSON 数据存储到数组中。

let data = JSON.parse('[{"address":"A-D-1","batch":[{"batch_number":"B-123","cost":[{"cost":"C1"}]}]},{"address":"A-85-1","batch":[{"batch_number":"B-6562","cost":[{"cost":"C16464"}]}]},{"address":"A-522-1","batch":[{"batch_number":"B-4511","cost":[{"cost":"C8745"}]}]}]');

for (let i = 0; i < data.length; i++) {

if (data[i].batch !== undefined && data[i].batch !== null && data[i].batch.length !== undefined && data[i].batch.length > 0) {
let batchLength = data[i].batch.length

let newObject = {}
let newArray = []

for (let j = 0; j < batchLength; j++) {
if (data[i].batch !== undefined && data[i].batch[j].cost !== null && data[i].batch[j].cost.length !== undefined && data[i].batch[j].cost.length > 0) {
let costLength = data[i].batch[j].cost.length
for (let k = 0; k < costLength; k++) {

newObject.location = data[i].address
newObject.batch.number = data[i].batch[j].batch_number ? data[i].batch[j].batch_number : ''

newObject.cogs = data[i].batch[j].cost[k].cost ? data[i].batch[j].cost[k].cost : ''
newArray.push(newObject)
}
}
}
}

}

我已将 JSON 存储在 data 变量中。

我试过下面的代码。但我总是将最后一个索引重复。

预期输出:

[
{
"address":"A-D-1",
"batch":{
"batch_number":"B-123"
},
"cost":"C1"
},
{
"address":"A-85-1",
"batch":{
"batch_number":"B-6562"
},
"cost":"C16464"
},
{
"address":"A-522-1",
"batch":{
"batch_number":"B-4511"
},
"cost":"C8745"
}
]

任何帮助都会很棒。

谢谢。

最佳答案

你的意思是这样的?

const someArray = [{
"address": "A-D-1",
"batch": [{
"batch_number": "B-123",
"cost": [{
"cost": "C1"
}]
}]
}, {
"address": "A-85-1",
"batch": [{
"batch_number": "B-6562",
"cost": [{
"cost": "C16464"
}]
}]
}, {
"address": "A-522-1",
"batch": [{
"batch_number": "B-4511",
"cost": [{
"cost": "C8745"
}]
}]
}]

console.log(someArray.map(item => {
return {
address:item.address,
batch_number: item.batch && item.batch[0].batch_number,
cost: item.batch && item.batch[0].cost[0].cost
}
}))

关于Javascript : Store JSON data in array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53379594/

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