Javascript对象数组输出

时间:2017-10-31 18:22:01

标签: javascript

 var input =[
  {make:"BMW", model:"320d"},
  {make:"TATA", model:"aria"},
  {make:"Maruti", model:"800"},
  {make:"Maruti", model:"wagnor"},
  {make:"BMW", model:"720d"},
  {make:"BMW", model:"320d"}  
];

var output ={};

说明:

我希望输出如下所示,就像基于相同键的值分组一样,没有重复值(唯一)。对象数组。此处不得出现重复值。我已经尝试了很多代码,但无法解决问题。

[object object]{  BMW:["320d","720d"],  Tata:['area']  Maruti:['800','wagonar'], }

2 个答案:

答案 0 :(得分:1)

由于OP不希望输出数组中出现重复:

ES6,版本1:

const input =[
  {make:"BMW", model:"320d"},
  {make:"TATA", model:"aria"},
  {make:"Maruti", model:"800"},
  {make:"Maruti", model:"wagnor"},
  {make:"BMW", model:"720d"},
  {make:"BMW", model:"320d"}  
];

const output = {};

for (const {make, model} of input) {
  // create empty list if this is the first time we've seen this make
  output[make] = output[make] || [];
  // only add model, once (no duplicates in our list)    
  if (!output[make].includes(model)) {
    output[make].push(model);
  }
}  

console.log(output)

或者,代替if (!output[item.make].includes(item.model)) { ...
您可以使用if (output[item.make].indexOf(item.model) === -1) { ...

ES5,版本2:

input =[
  {make:"BMW", model:"320d"},
  {make:"TATA", model:"aria"},
  {make:"Maruti", model:"800"},
  {make:"Maruti", model:"wagnor"},
  {make:"BMW", model:"720d"},
  {make:"BMW", model:"320d"}  
];

output = {};

input.forEach(function(item) {
  // create a new list if this is the first time we've seen this make
  if (!output[item.make]) { 
    output[item.make] = [item.model] 
  }
  // only add model, once (no duplicates in our list)
  else if (output[item.make].indexOf(item.model) === -1) {
    output[item.make].push(item.model)
  }
})

console.log(output)

答案 1 :(得分:-2)

const input =[
  {make:"BMW", model:"320d"},
  {make:"TATA", model:"aria"},
  {make:"Maruti", model:"800"},
  {make:"Maruti", model:"wagnor"},
  {make:"BMW", model:"720d"},
  {make:"BMW", model:"320d"}  
];

const output = {};
const mem = {};

input.forEach((item) => {
  if(!output[item.make]) {output[item.make] = [] }
  if (mem[item.model] != item.make) {
    output[item.make].push(item.model)
  }
  mem[item.model] = item.make;
})

console.log(output)