使用ES6进行JSON对象重组

时间:2018-06-22 07:49:54

标签: javascript json ecmascript-6

我有这样的东西:

tires: [{
  name: "fancyProduct1",
  quantity: 1
}, {
  name: "fancyProduct1",
  quantity: 1
}, {
  name: "fancyProduct1",
  quantity: 1
}, {
  name: "fancyProduct2",
  quantity: 1
}];

我要完成的是

tires: [{
  name: "fancyProduct1",
  quantity: 3
}, {
  name: "fancyProduct2",
  quantity: 1
}]

有什么最佳方法的想法吗?

4 个答案:

答案 0 :(得分:4)

您可以使用reduce将数组分组为一个对象。使用Object.values将对象转换为数组。

let tires = [{"name":"fancyProduct1","quantity":1},{"name":"fancyProduct1","quantity":1},{"name":"fancyProduct1","quantity":1},{"name":"fancyProduct2","quantity":1}];

let result = Object.values(tires.reduce((c, {name,quantity}) => {
  c[name] = c[name] || {name,quantity: 0}
  c[name].quantity += quantity;
  return c;
}, {}));

console.log(result);

答案 1 :(得分:1)

使用Reduce将完成此操作:

var products = { tires: [ {name: "fancyProduct1", quantity: 1}, {name: "fancyProduct1", quantity: 1}, {name: "fancyProduct1", quantity: 1}, {name: "fancyProduct2", quantity: 1}] };

var result = products.tires.reduce((acc,current) => {

    if (!acc[current.name]) {
       acc[current.name] = { name: current.name, quantity: 0};
    }

    acc[current.name].quantity++;

    return acc;
}, {});

var resultArray = Object.values(result);
console.log(resultArray);

答案 2 :(得分:1)

好吧,您可以使用简单的Array.forEach()调用来循环array项,并与Array.find()一起检查{{ 1}}数组并相应地执行逻辑。

这应该是您的代码:

item

演示:

result

答案 3 :(得分:-1)

您可以执行以下操作...

var newTries = tires.map(n => (
 // logic for new array where you can get attributes of item in tires to create a new array. 
console.log(n);  // this can show what properties are available in the current item write it to the console. 
)};

希望这会有所帮助。