【问题标题】:How to loop through array of objects and make key value pairs?如何遍历对象数组并制作键值对?
【发布时间】:2020-10-02 05:26:20
【问题描述】:

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

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

【问题讨论】:

标签: javascript arrays object


【解决方案1】:

您可以使用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 将对象转换为pairs,然后使用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)

【讨论】:

    【解决方案2】:

    您可以从 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);

    【讨论】:

      【解决方案3】:

      使用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));

      【讨论】:

      • 嘿,很好的答案。它在概念上与我的第三次拍摄(功能性拍摄)stackoverflow.com/a/62343622/411632 相似,但你的是最简单的。完美,除非项目有超过 2 个属性。在这种情况下,我的固定映射仍然可以工作。无论如何,您的答案应该是 OP 选择的答案。
      • 谢谢@MatíasFidemraizer,同意你的看法。我喜欢你详细的概念和答案。
      【解决方案4】:

      首先,您可以将itens转换为“KV”条目

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

      然后把它变成Object

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

      那么您的函数将适用于任何iterable

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-21
        • 2021-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-08
        相关资源
        最近更新 更多