【问题标题】:Convert array object into object in Javascript在Javascript中将数组对象转换为对象
【发布时间】:2021-07-01 08:17:40
【问题描述】:

我正在尝试将一个数组对象转换为与当前对象的 filterKey 和 filterValue 匹配的对象数组。

[
    {
        "filterKey": "name",
        "filterValue": [
            {
                "value": "abc"
            },
             {
                "value": "def"
            }
        ]
    },
    {
        "filterKey": "status",
        "filterValue": [
            {
                "value": "active"
            },
            {
                "value": "pending"
            }
        ]
    }
]

我期待的结果如下:

{
    "name": [
        "abc",
        "def"
    ],
    "statuses": [
        "active",
        "pending"
    ]
}

我试过了

obj.map(item => Object.values(item.filterValue))

【问题讨论】:

    标签: javascript arrays javascript-objects


    【解决方案1】:

    reduce 覆盖数据数组,并创建一个新对象,使用map 为每个新属性创建一个新的值数组。

    const data=[{filterKey:'name',filterValue:[{value:'abc'},{value:'def'}]},{filterKey:'status',filterValue:[{value:'active'},{value:'pending'}]}];
    
    // Iterate over the array with `reduce`
    const out = data.reduce((acc, obj) => {
    
      // Extract the key and value from each object
      const { filterKey: key, filterValue: value } = obj;
    
      // Return the accumulator object updated with the new key
      // and array of values gained from `map`
      return {...acc, [key]: value.map(o => o.value)};
    }, {});
    
    console.log(out);

    【讨论】:

      【解决方案2】:

      const oldArr = [{"filterKey": "name","filterValue": [{"value": "abc"},{"value": "def"}]},{"filterKey": "status","filterValue": [{"value": "active"},{"value": "pending"}]}];
      
      const newObj = oldArr.reduce((a, b) => { // reduce to single object
        const values = b.filterValue.map(x => x.value); // map the filter values to their strings
        if (a[b.filterKey]) a[b.filterKey].concat(values); // if the key already exists add the strings to it (does not apply to your example)
        else a[b.filterKey] = values; // else create a new entry with the strings
        return a;
      }, {});
      
      // if you really want to rename status => statuses
      newObj.statuses = newObj.status;
      delete newObj.status;
      
      console.log(newObj);

      【讨论】:

        猜你喜欢
        • 2017-01-14
        • 1970-01-01
        • 2019-10-22
        • 2018-01-24
        • 1970-01-01
        • 2021-09-09
        • 2018-08-21
        • 1970-01-01
        相关资源
        最近更新 更多