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

时间:2018-05-10 03:43:01

标签: javascript arrays javascript-objects

我有像

这样的行中的数据
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 ['喘气']

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

2 个答案:

答案 0 :(得分:5)

使用数组缩减功能并按名称pant创建密钥。检查密钥是否存在,然后推送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)




答案 1 :(得分:1)

如果您想使用type作为对象的键,而值是serviceprice的数组,则可以使用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);