从对象数组中提取选定的对象并创建新的数组

时间:2019-09-26 14:02:14

标签: javascript arrays object javascript-objects clone

我有一个像这样的对象数组:

var myArray = [
  {"domain":"mysite.es","id":12,"selected":false},
  {"domain":"mysite.bg","id":51,"selected":false},
  {"domain":"mysite.uk","id":41,"selected":false},
  {"domain":"mysite.bg","id":36,"selected":false},
  {"domain":"mysite.pt","id":14,"selected":false},
  {"domain":"mysite.it","id":78,"selected":false},
  {"domain":"mysite.gr","id":71,"selected":false},
  {"domain":"mysite.dr","id":73,"selected":false}
]

我需要使用选定的对象从myArray创建三个新的数组。例如:

firstArrayFromMyArray 将包含索引为0、2和4的对象。 secondArrayFromMyArray 将包含索引为1和4的对象。 和 thirdArrayFromMyArray 将包含索引为6和7的对象

按照上面的示例,firstArrayFromMyArray的输出应如下所示:

firstArrayFromMyArray = [
  {"domain":"mysite.es","id":12,"selected":false},
  {"domain":"mysite.uk","id":41,"selected":false},
  {"domain":"mysite.pt","id":14,"selected":false}
]

做这件事的最佳方法是什么?

3 个答案:

答案 0 :(得分:1)

您可以为每个索引获取一个带有目标的对象,然后将所需的对象推到新的外部索引。

#priceMonthly

答案 1 :(得分:0)

var myArray = [
  {"domain":"mysite.es","id":12,"selected":false},
  {"domain":"mysite.bg","id":51,"selected":false},
  {"domain":"mysite.uk","id":41,"selected":false},
  {"domain":"mysite.bg","id":36,"selected":false},
  {"domain":"mysite.pt","id":14,"selected":false},
  {"domain":"mysite.it","id":78,"selected":false},
  {"domain":"mysite.gr","id":71,"selected":false},
  {"domain":"mysite.dr","id":73,"selected":false}
];

function get3Arrays(myArray)
{
	let ary = [];
	ary.push([myArray[0], myArray[2], myArray[5]]);
	ary.push([myArray[1], myArray[4]]);
	ary.push([myArray[6], myArray[7]]);
	return ary;
}

let aryOfArrays = get3Arrays(myArray);

console.log('1st Array', aryOfArrays[0]);
console.log('2nd Array', aryOfArrays[1]);
console.log('3rd Array', aryOfArrays[2]);

答案 2 :(得分:-1)

我建议使用reduce

const {
  firstArrayFromMyArray,
  secondArrayFromMyArray,
  thirdArrayFromMyArray,
} = myArray.reduce((acc, ele, index) => {
  if (index === 0 || index === 2 || index === 5) {
    acc.firstArrayFromMyArray.push(ele);
  } else if (index === 1 || index === 4) {
    acc.secondArrayFromMyArray.push(ele);
  } else if (index === 6 || index === 7) {
    acc.thirdArrayFromMyArray.push(ele);
  }
  return acc;
}, {
  firstArrayFromMyArray: [],
  secondArrayFromMyArray: [],
  thirdArrayFromMyArray: [],
});