2017-09-06 58 views
0

我從後臺發送下列對象轉化列表,多選值控制

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

我需要將其轉換爲

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

所以,你可以看到,我想放收到的值通過收到的ID多選控件和索引值。您也瞭解我:name應該以多選形式顯示。
如何做到這一點?

+0

什麼是'selected'(至於你的問題而言)?這只是一個空數組,以便附加到'transformedObjects'以供以後使用? – skylize

+0

'id:{name,secondName}'這是無效的JSON? –

+0

@skylize,是的 –

回答

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>