我有像
这样的行中的数据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 ['喘气']
获得所有类型的服务及其价格答案 0 :(得分:5)
使用数组缩减功能并按名称pant
创建密钥。检查密钥是否存在,然后推送service
和price
预期对象也无效。对象键由冒号(:
)分隔
以这种格式
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)

答案 1 :(得分:1)
如果您想使用type
作为对象的键,而值是service
和price
的数组,则可以使用reduce
let arr = [{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"}];
let result = arr.reduce((c, {type,...r}) => {
c[type] = c[type] || [];
c[type].push(r);
return c;
}, {});
console.log(result);