【问题标题】:How do I convert an object into an array of objects where the objects in the array should be the key value pairs of the original object? [duplicate]如何将对象转换为对象数组,其中数组中的对象应该是原始对象的键值对? [复制]
【发布时间】:2023-02-02 19:55:29
【问题描述】:

我有以下对象

input = {a:1, b:2, c:3}

我想将其转换为以下内容

Output = [{ a: 1 }, { b: 2 }, { c: 3 }]

还提供反之亦然的解决方案,即对象数组到对象。

我曾尝试使用 Object.entries 等内置方法,但没有得到完美的解决方案。

【问题讨论】:

标签: javascript arrays javascript-objects


【解决方案1】:

使用 Object.entries() 获取键/值元组并根据需要格式化它们:

const input = {a:1, b:2, c:3}
const res = Object.entries(input).map(([key, value]) => ({[key]: value}))
console.log(res)

【讨论】:

    【解决方案2】:

    您可以使用 Object.entries 获取 keyvalue 对,然后从中形成对象。

    要从数组转换 obj,您只需迭代到数组并从中创建一个对象。

    您可以检查此解决方案。

    input = {a:1, b:2, c:3}
    
    function obj2arr(obj) {
        return Object.entries(obj).map(([key, value]) => {
            return {[key]: value}
        })
    }
    
    function arr2obj(arr) {
        return arr.reduce((resObj, obj) => {
            return {...resObj, ...obj};
        }, {});
    }
    
    const arr = obj2arr(input);
    const obj = arr2obj(arr);
    
    console.log(arr);
    console.log(obj);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-26
      • 2017-09-23
      • 2018-05-10
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多