gpt4 book ai didi

javascript - JS 通过嵌套的 json 创建自定义 json

转载 作者:行者123 更新时间:2023-11-29 23:16:49 24 4
gpt4 key购买 nike

在这里,我需要将我的嵌套 JSON 转换为没有嵌套对象的自定义 JSON。

function transform(){  
let items = [
{
"carId":328288,
"firstName":"yathindra",
"lastName":"rawya",
"list":[
{
"id":182396,
"isAvail":false,
"stateId":288,
"state":"Awesome"
},
{
"id":182396,
"isAvail":false,
"stateId":678,
"state":"Cool1"
}
],
},
{
"carId":3282488,
"firstName":"yathindraR",
"lastName":"K",
"list":[
{
"id":18232396,
"isAvail":false,
"stateId":22388,
"state":"Awesome"
},
{
"id":182356796,
"isAvail":false,
"stateId":45678,
"state":"Cool"
}
],
}
]

let customList = [];

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

let temp = new Array()
for(let j=0;j<items[i].list.length;j++){
temp.push(
items[i].list[j].state
)
}

customList.push({
fname: items[i].firstName,
lname: items[i].lastName,
...temp
})
}

console.log(JSON.stringify(customList))
}

transform();

下面是我得到的输出。

[{"0":"Awesome","1":"Cool1","fname":"yathindra","lname":"rawya"},{"0":"Awesome","1":"Cool","fname":"yathindraR","lname":"K"}]

但我不想一开始就将项目放在临时数组中。我希望他们最后放置。像这样的东西。

[{"fname":"yathindra","lname":"rawya","0":"Awesome","1":"Cool1"},{"fname":"yathindraR","lname":"K","0":"Awesome","1":"Cool"}]

这里不需要使用数字作为临时数组中的键。因为我只想要每个值。 所以如果所有的键都是字符串并且值的顺序很重要。如何做到这一点?

最佳答案

请将您的代码替换为以下代码,它将立即生效。键将是“state-1”、“state-2”而不是“0”、“1”

function transform(){  
let items = [
{
"carId":328288,
"firstName":"yathindra",
"lastName":"rawya",
"list":[
{
"id":182396,
"isAvail":false,
"stateId":288,
"state":"Awesome"
},
{
"id":182396,
"isAvail":false,
"stateId":678,
"state":"Cool1"
}
],
},
{
"carId":3282488,
"firstName":"yathindraR",
"lastName":"K",
"list":[
{
"id":18232396,
"isAvail":false,
"stateId":22388,
"state":"Awesome"
},
{
"id":182356796,
"isAvail":false,
"stateId":45678,
"state":"Cool"
}
],
}
]

let customList = [];

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

let temp = {};
for(let j=0;j<items[i].list.length;j++){
temp["state-"+(j+1)] = items[i].list[j].state;
}

customList.push({
fname: items[i].firstName,
lname: items[i].lastName,
...temp
})
}

console.log(JSON.stringify(customList))
}

transform();

关于javascript - JS 通过嵌套的 json 创建自定义 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52453330/

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