[英]How can i prepare nested key value pair list in JavaScript
I have data in rows like 我有像这样的行中的数据
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"}
Looking for something like 寻找类似的东西
var x = {"pant", [{service:"normal", price:"30"},{service:"premium 1", price:"50"} ,{service:"premium 2", price:"70"}, {service:"premium 3", price:"100"}]}
so that I can get all type of services and their price by doing x['pant'] 这样我就可以通过执行x ['pant']获得所有类型的服务及其价格
Use array reduce function and create a key by name pant
. 使用数组归约功能并通过名称
pant
创建一个键。 Check if the key exist then push the value of service
and price
检查密钥是否存在,然后推送
service
和price
的值
Also the expected object is invalid. 同样,预期对象无效。 An object key is separated by a colon (
:
) in this format (一个对象密钥由冒号分开
:
在该格式)
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)
If you want to use type
as the key of the object and the values are arrays of service
and price
, you can use reduce
如果要使用
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.