gpt4 book ai didi

javascript - 我如何在 JavaScript 中准备嵌套键值对列表

转载 作者:行者123 更新时间:2023-11-28 12:15:35 25 4
gpt4 key购买 nike

我的数据行如

1. {type:"pant", service:"normal", price:"30"}
2. {type:"pant", service:"premium 1", price:"50"}
3. {type:"pant", service:"premium 2", price:"70"}
4. {type:"pant", service:"premium 3", price:"100"}

寻找类似的东西

var x = {"pant", [{service:"normal", price:"30"},{service:"premium 1", price:"50"} ,{service:"premium 2", price:"70"}, {service:"premium 3", price:"100"}]}

这样我就可以通过执行x['pant']

来获得所有类型的服务及其价格

最佳答案

使用数组reduce函数并按名称pant创建一个键。检查 key 是否存在,然后推送 serviceprice

的值

预期的对象也是无效的。对象键由冒号分隔 (:)按照这种格式

obj = {
key:value
}

var data = [{
type: "pant",
service: "normal",
price: "30"
}, {
type: "pant",
service: "premium 1",
price: "50"
}, {
type: "pant",
service: "premium 2",
price: "70"
}, {
type: "pant",
service: "premium 3",
price: "100"
}]

var x = data.reduce(function(acc, curr, currIndex) {
if (!acc[curr.type]) {
acc[curr.type] = []
}

acc[curr.type].push({
service: curr.service,
price: curr.price
})

return acc;


}, {});

console.log(x)

关于javascript - 我如何在 JavaScript 中准备嵌套键值对列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50265131/

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