如何循环遍历对象数组并创建键值对?

3

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

let someObj = {
    items: [{
        id: '12',
        value: true
    }, {
        id: '34',
        value: true
    }, {
        id: '56',
        value: false
    }]

}

我想将这个内容添加到现有对象中,其中id是这个对象的一个键,就像这样:

let obj = {
    someKey: someValue,
    '12': true,
    '34': true,
    '56': false,
}

2
你具体遇到了什么问题?你知道如何迭代数组吗?你知道如何访问对象的属性吗?你知道如何向对象添加属性吗? - Felix Kling
4个回答

4
您可以使用 Array#reduce 来达到您的目标,方法如下:

const input = {
  items: [{
    id: '12',
    value: true
  }, {
    id: '34',
    value: true
  }, {
    id: '56',
    value: false
  }]
}

const output = input.items.reduce((o, {
  id,
  value
}) => (o[id] = value, o), {})

console.log(output)

另外,最简单的方法可能是使用Array#map将对象转换为键值对,然后使用Object.fromPairs将它们转换为一个对象:

const input = {
  items: [{
    id: '12',
    value: true
  }, {
    id: '34',
    value: true
  }, {
    id: '56',
    value: false
  }]
}

const output = Object.fromEntries(input.items.map(({
  id,
  value
}) => [id, value]))

console.log(output)

最后,这是一种函数式的方法:

  // Composes two functions
  const compose = f => g => x => f (g (x))

  // Given the key-value pairs of some object with 2 properties, maps a pair of values
  const values = ([[, x], [, y]]) => [x, y]

  // Turns an object of two properties into a pair of property values
  const entry = compose (values) (Object.entries)

  // Turns many objects of two properties, into an object on which
  // keys are first properties' values, and vaules the second properties' values.
  const keyValueObject = xs => Object.fromEntries (xs.map (entry))

  const input = {
    items: [{
      id: '12',
      value: true
    }, {
      id: '34',
      value: true
    }, {
      id: '56',
      value: false
    }]
  }

  const output = keyValueObject (input.items)

  console.log(output)


1
你可以从items中迭代每个项,并按如下所示创建一个新对象。

let someObj = {
    items: [{
        id: '12',
        value: true
    }, {
        id: '34',
        value: true
    }, {
        id: '56',
        value: false
    }]

}
const newObj = {};
someObj.items.map(item =>{
newObj[item.id]= item.value;
});

console.log(newObj);


1
使用 mapObject.values 可以简化代码。

const output = arr => Object.fromEntries(arr.map(Object.values));

let someObj = {
  items: [
    {
      id: "12",
      value: true,
    },
    {
      id: "34",
      value: true,
    },
    {
      id: "56",
      value: false,
    },
  ],
};


console.log(output(someObj.items));


1
嘿,答案很好。从概念上讲,它与我的第三个方法(函数式)https://dev59.com/17voa4cB1Zd3GeqP6ZJI#62343622类似,但是你的方法最简单。如果项目有多于2个属性,那么我修复后的映射仍然有效。无论如何,你的回答应该是被提问者选择的。 - Matías Fidemraizer
1
谢谢@MatíasFidemraizer,我同意你的观点。我喜欢你详细的概念和答案。 - Siva K V

0
首先,您可以将项目转换为“KV”条目。
> someObj.items.map(({id, value}) => [id, value])
[ [ '12', true ], [ '34', true ], [ '56', false ] ]

然后将其转换为对象

> Object.fromEntries(someObj.items.map(({id, value}) => [id, value]))
{ '12': true, '34': true, '56': false }

你可以编写一个函数

> let ObjectFromMapping = (vs, mapping) => Object.fromEntries(vs.map(mapping))
> ObjectFromMapping(someObj.items, ({id, value}) => [id, value])
{ '12': true, '34': true, '56': false }

或许将 vs 转换为可迭代对象是个好主意

> let ObjectFromMapping = (vs, mapping) => Object.fromEntries([... vs].map(mapping))
> ObjectFromMapping("abc", (char, idx) =>  [idx, char])
{ '0': 'a', '1': 'b', '2': 'c' }

然后你的函数就可以在任何可迭代对象上运行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接