【问题标题】:Creating an array of objects in JS在 JS 中创建对象数组
【发布时间】:2018-08-17 14:37:01
【问题描述】:

我有 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 为真,对于给定名称,至少有一个值不同。

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

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
})

【问题讨论】:

  • 这对我来说看起来很不错 - 你能更具体地谈谈“更简单”的方式吗?您有性能问题吗?
  • 旁注如果变量要更改,则不应使用 const 定义变量,因为它是可变数据类型,不会引发任何错误。

标签: javascript arrays object compare


【解决方案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)

【讨论】:

    【解决方案2】:

    你可以看看javascriptreduce数组方法。 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(()=>{}))
    },[])

    【讨论】:

    • 你的代码产生Uncaught TypeError: curr.forEach is not a function
    • 这不是一个直接的解决方案,它是如何解决这个问题的一个例子
    猜你喜欢
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    相关资源
    最近更新 更多