gpt4 book ai didi

javascript - 在 javascript 中使用 map 更改数组

转载 作者:行者123 更新时间:2023-11-28 10:42:54 26 4
gpt4 key购买 nike

这是我的 json 对象:

{
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
}

我想要这样的输出:

{
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"cats": [1,2] // this 1 and 2 is coming from categoriesservices array inside the category object i have id
}

如何使用 map 功能做到这一点?我是 javascript 新手,map 或 forloop 哪个是好的方法?

最佳答案

参见destructuring assignment , Array.prototype.map() ,和 JSON了解更多信息。

// Input.
const input = {
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
}

// Categories => Objects to Cats => Ids.
const output = (input) => JSON.parse(JSON.stringify({
...input,
cats: input.categoryservices.map(({category: {id}}) => id),
categoryservices: undefined
}))

// Log.
console.log(output(input))

关于javascript - 在 javascript 中使用 map 更改数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49273545/

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