基于元素的Javascript中的对象数组

时间:2016-08-05 11:07:33

标签: javascript

假设我有1000个物体。现在我想在数组中存储具有相同名称的对象,这样我将拥有多个具有相同名称的对象的数组。如何在JavaScript中完成? 数据可以是这样的

Data can be like this

2 个答案:

答案 0 :(得分:1)

    var input = [
        { name: 'ABC', age: 12 },
        { name: 'XYZ', age: 13 },
        { name: 'ABC', age: 14 },
        { name: 'XYZ', age: 15 },
    ];
    
    var output = {};
    
    input.forEach(function(obj) {
       var array = output[obj.name];
    
       if (!array) {
          array = output[obj.name] = [];
       }
    
       array.push(obj)
    })

    for(name in output) {
        console.log('There are ' + output[name].length + ' people named ' + name);
    }

答案 1 :(得分:-1)

In javascript, objects aren't copied into arrays. They exist in memory and when added to a an array the reference to that object is what lives in an array.

In the following code, myObj === arr1[0] === arr2. Which means the following is true:

var myObj = {name:'Dave', age: 55};
var arr1 = [myObj];
var arr2 = [myObj];

arr2[0].age = 44;
console.log(myObj.age);
// prints 44
console.log(arr1[0].age);
// prints 44

So to get what you need, you just need to organize your data into arrays. In javascript, you can filter arrays:

// original data
var data = [
 {name: 'ABC', age: 12},
 {name: 'XYZ', age: 13},
 {name: 'ABC', age: 14},
 {name: 'XYZ', age: 15},
 {name: 'XYZ', age: 16},
];
    
// this returns a function to be used in Array.filter to filter for objects with the specified name
function nameFilter(name) {
  return function(datum) {
    return datum.name === name;
  }
}
    
// filter for each type
var abcPeople = data.filter(nameFilter('ABC'));
var xyzPeople = data.filter(nameFilter('XYZ'));
      
console.log(data.length);
//5
console.log(abcPeople.length);
//2
console.log(xyzPeople.length);
//3
      

If you run the above code, you would have 3 arrays and all object in abcPeople would also be in data such that any change to one would be reflected in the other. The same is true for xyzPeople. Just to be clear, filter creates a new array, so data is not modified.

UPDATE: Added example where lists are dynamically determined

// original data
var data = [
  {name: 'ABC', age: 12},
  {name: 'XYZ', age: 13},
  {name: 'ABC', age: 14},
  {name: 'XYZ', age: 15},
  {name: 'XYZ', age: 16},
];
      
var sortedData = {};
  
data.forEach(function(datum){
  // initializes an array for any unseen name
  if(!sortedData[datum.name]) {
    sortedData[datum.name] = [];
  }
  // add the datum to the list for its name
  sortedData[datum.name].push(datum);
});

// all names
console.log(Object.keys(sortedData));
// "ABC", "XYZ"

// items named "ABC"
console.log(sortedData['ABC']);
// [{"name": "ABC","age": 12}, {"name": "ABC","age": 14}]