【问题标题】:How to convert array of objects to object with index?如何将对象数组转换为具有索引的对象?
【发布时间】:2017-11-07 01:21:27
【问题描述】:

我有一个这样的数组->

var jsonResponse = [
     {   
        "name": "abc",
        "value": [
            { "label" : "Daily", "value":"Daily"}         
        ]
    },
    {   
        "name": "ccc",
        "value": [
            { "label" : "Daily", "value":"Daily"}         
        ]
    }
]

我想把它转换成->

{
    "abc" : {   
        "name": "abc",
        "value": [
            { "label" : "Daily", "value":"Daily"}         
        ]
    },
    "ccc": {   
        "name": "ccc",
        "value": [
            { "label" : "Daily", "value":"Daily"}         
        ]
    }
]

可能我不想要 foreach。 我们可以使用 Object.assign(arrayDetails, ...jsonResponse); 但是如何做对象索引呢?

【问题讨论】:

    标签: javascript spread-syntax


    【解决方案1】:
    let indexedResult = {};
    jsonResponse.map(obj => indexedResult[obj.name] = obj)
    
    console.log(JSON.stringify(indexedResult));
    

    【讨论】:

      猜你喜欢
      • 2021-12-10
      • 2020-07-28
      • 2017-09-23
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多