在JS中创建对象数组

时间:2018-08-17 14:37:02

标签: javascript arrays object compare

我有2个数组:

let array1 = ["a", "b", "c"]
const array2 = [{a: 23, b: 22, c: 14}, {a: 78, b: 22, c: 14}, {id: 3, a: 23, b: 80, c: 14}]

我需要根据以下条件更新array1:
对于数组中的每个元素,我需要返回一个对象:

[{name: 'a', isDifferent: true}, {name: 'b', isDifferent: true}, {name: 'c', isDifferent: false}]

其中isDifferent为true,对于给定名称,至少一个值不同。

这是我的职责。有效。
但是我认为有更简单的方法可以做到这一点。

array1 = array1.map(el => {
 const newObj = {}
 newObj.name = el
 let isDifferent = false
 for (let i = 0; i < array2.length; i++) {
  if (array2[i][el] !== array2[0][el]) {
    isDifferent = true
    break
  }
 }
 newObj.isDifferent = isDifferent
 return newObj
})

2 个答案:

答案 0 :(得分:1)

这是一种方法:

const array1 = ["a", "b", "c"]
const array2 = [{a: 23, b: 22, c: 14}, {a: 78, b: 22, c: 14}, {id: 3, a: 23, b: 80, c: 14}]

let result = array1.map( letter => {
	let values = array2.map(obj => obj[letter]); // Getting [23, 78, 3] for "a"
	return {
		name : letter,
		isDifferent : !values.every(v => v===values[0]) // Checks if every value in the array equals the first one
	}
})

console.log(result)

答案 1 :(得分:-3)

您可以看一下JavaScript reduce数组方法。 reduce

const array2 = [{a: 23, b: 22, c: 14}, {a: 78, b: 22, c: 14}, {id: 3, a: 23, b: 80, c: 14}]

const arr = array2.reduce((acc,curr)=>{
     acc.push(curr.forEach(()=>{}))
},[])