将对象列表转换为多选值控件

时间:2017-09-06 06:03:58

标签: javascript angularjs

我有从后端发送的以下对象

[ {
    id : integer,
    name : string
    secondName : string
  }
]

我需要将其转换为

  transformedObjects = {
        options: {
            id: {name, secondName}
            id: {name, secondName}
        ...
        },
        selected: []
    };

因此,正如您所看到的,我希望通过接收到的id将接收到的值放在多选控制和索引值上。您也理解我:name应该以多选方式显示 怎么做 ?

1 个答案:

答案 0 :(得分:0)

结帐Array.prototype.reduce()以了解有关减少数组的详情。或者类似于How reduce works, when to use it这样的学术方法。



    // sample data so we can run the code
    const objs = [
      {
        id : 105,
        name : 'fluffy',
        secondName : 'fluffykins'
      },
      {
        id : 'id#1527',
        name : 'rabbit',
        secondName : 'rabbithole'
      }
    ]

    // Transform array with a reduce calling a function on each item
    //  `acc` is an accumulator, we keep adding to that object 
    //  each time through the loop and return it so it can be passed
    //  into the next loop, obj is the individual object being 
    //  worked on.

    const options = objs.reduce((acc, obj) => {
      acc[obj.id] = {
        name: obj.name,
        secondName: obj.secondName
      }
      return acc
    }, {})

    // Then we can just tack on the `selected` array. It is possible
    //  to shove this part inside the reduce function, but it will 
    //  just make your code much harder to read with no obvious benefit.
    transformedObjects = {
      options,
      selected: []
    }

    // Display results. We are converting to JSON here, so numbered keys will look like strings.
    document.querySelector('#output').innerText = JSON.stringify(transformedObjects, null, 2)

transformedObjects = 
<!-- a preformatted text element to display results in -->
<pre id='output'></pre>
&#13;
&#13;
&#13;