如何从另一个数组中的对象属性创建数组

时间:2018-05-01 22:37:11

标签: javascript arrays

我有一个对象数组,我想根据数组中对象的属性将其分解为另一组数组。

例如,我有一些这样的对象:

function Object1(property1, property2, property3){
this.property1 = property1;
this.property2 = property2;
this.property3 = property3;
}

然后,我有一个包含其中几个对象的数组,但是有些对象共享property1的相同值,例如:

const obj1 = new Object1(id_1, some_value_1, some_value_2);
const obj2 = new Object1(id_2, some_value_2, some_value_2);
const obj3 = new Object1(id_1, some_value_3, some_value_3);
const obj4 = new Object1(id_2, some_value_4, some_value_4);

var objectArray = [obj1, obj2, obj3, obj4];

现在给定这个数组,我想基于Object1.property1创建新的数组,以便最终得到以下数组:

array1 = [obj1, obj3];
array2 = [obj2, obj4];

这无疑不是一项任务,但我无法想到。感谢您的投入。

有一两个警告:我不会总是知道objectArray有多大,我不知道该数组中有多少个对象共享一个属性,这意味着需要x个新数组。

3 个答案:

答案 0 :(得分:1)

您可以使用reduce按特定属性对对象进行分组:



function Object1(property1, property2, property3) {
  this.property1 = property1;
  this.property2 = property2;
  this.property3 = property3;
}

const obj1 = new Object1('id_1', 'some_value_1', 'some_value_2');
const obj2 = new Object1('id_2', 'some_value_2', 'some_value_2');
const obj3 = new Object1('id_1', 'some_value_3', 'some_value_3');
const obj4 = new Object1('id_2', 'some_value_4', 'some_value_4');

const objectArray = [obj1, obj2, obj3, obj4];

const outputObj = objectArray.reduce((accum, obj) => {
  const id = obj.property1;
  if (!accum[id]) accum[id] = [];
  accum[id].push(obj);
  return accum;
}, []);

const [array1, array2] = Object.values(outputObj);
console.log(array1);
console.log(array2);




您还应注意不要混用constvar - 如果您要使用ES6,请始终使用const(并且很少使用let ,当需要重新分配时。)

答案 1 :(得分:1)

为简单起见,我将内联创建数组和对象。

这将在两次通过中完成。首先,用prop1将prop2和prop3分组。然后,过滤掉每个组的唯一元素。

var things = [
  {prop1: 1, prop2: 'a', prop3: 'b'},
  {prop1: 2, prop2: 'b', prop3: 'b'},
  {prop1: 1, prop2: 'c', prop3: 'c'},
  {prop1: 2, prop2: 'd', prop3: 'd'}
];

var grouped = things.reduce(function (groups, thing) {
  groups[thing.prop1] = groups[thing.prop1] || [];
  groups[thing.prop1].push(thing.prop2);
  groups[thing.prop1].push(thing.prop3);
  return groups;
}, {});

/*
We are now grouped by prop1.
{
1: ["a", "b", "c", "c"],
2: ["b", "b", "d", "d"]
}
*/

var groupedAndUniq = Object.keys(grouped).reduce(function (groups, key) {
  groups[key] = [...new Set(grouped[key])];
  return groups;
}, {});

console.log(groupedAndUniq);

/*
We are now grouped and unique.
{
1: ["a", "b", "c"],
2: ["b", "d"]
}
*/

答案 2 :(得分:0)

您可以使用.filter()根据属性值选择数组中的对象:



function Object1(property1, property2, property3) {
  this.property1 = property1;
  this.property2 = property2;
  this.property3 = property3;
}

const obj1 = new Object1(1, 'a', 'A');
const obj2 = new Object1(2, 'b', 'B');
const obj3 = new Object1(1, 'c', 'C');
const obj4 = new Object1(2, 'd', 'D');

const objectArray = [obj1, obj2, obj3, obj4];

const array1 = objectArray.filter(e => e.property1 == 1)
const array2 = objectArray.filter(e => e.property1 == 2)

console.log(array1)
console.log(array2)