将内部数组的对象数组更改为一个对象 [英] Change array of objects with array inside, to one object

查看:47
本文介绍了将内部数组的对象数组更改为一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,其中包含另一个数组,我想像这样将更大的数组转换为一个对象:

I have an array of objects, with another array inside them, and I want to convert the bigger array to one object like so:

[{
name: "test"
options: [
0: {id: "1", value: ""}
1: {id: "2", value: ""}
2: {id: "3", value: ""}
3: {id: "4", value: ""}]
}]

我希望最终结果像这样:

I want the final result to be like this:

{
  test: [
    {id: "1", value: ""},
    {id: "2", value: ""},
    {id: "3", value: ""},
    {id: "4", value: ""}
  ]
}

最好的方法是什么?

推荐答案

使用 reduce 进行对象创建

reduce 接受一个函数作为参数,该函数可以接受多个参数(至少2个),首先称为 accumulator ,它包含该函数先前所有调用的总和,第二个参数为 c urrent ,它包含一个当前值,在本例中是我们要转换的当前对象。如您所见,在 reduce 的末尾有一个 {} ,这是 initialValue 表示在 reduce 内部的该函数的第一次运行时,累加器就是这个值,因此 {} (空对象)

reduce takes a function as an argument and this function can take several arguments (at least 2), first is called an accumulator, it contains all sum of all previous calls of this function and the second argument is current, it contains a current value, in this case current object which we want to transform. As you can see, there is a {} in the end of reduce and this is initialValue which means that at first run of that function which is inside reduce, accumulator will be this value, so {} (empty object)

var arr = [
  {
    name: "test",
    options: [
      {id: "1", value: ""},
      {id: "2", value: ""},
      {id: "3", value: ""},
      {id: "4", value: ""}
    ]
  },
  {
    name: "test2",
    options: [
      {id: "12", value: ""},
      {id: "23", value: ""},
      {id: "34", value: ""},
      {id: "45", value: ""}
    ]
  }
]

var obj = arr.reduce((obj1, { name, options }) => ({...obj1, [name]: options}), {})

console.log(obj)

这篇关于将内部数组的对象数组更改为一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆