简体   繁体   中英

How to push object data in array

I have an object:

{background: "#f3f3f3", color: "#f435"}

And i have an array:

elData = {
   colors: [],
}

I want push object(key:val) to array.

Finaly data should be:

elData = {
   colors: [
     {background: "#f3f3f3"},
     {color: "#f435"}
   ],
}

how i can do that?

The trick is to first break down the original object into new objects of its component parts. Then add each component part into a new object and push that onto the array inside of ElData

 oldObject = {background: "#f3f3f3", color: "#f435"} colors=[]; elData = { colors: [], } Object.keys(oldObject).map(function(oldKey, index) { var value = oldObject[oldKey]; newObject={}; newObject={oldKey:value} elData.colors.push(newObject); }); console.log(elData); /* elData = { colors: [ {background: "#f3f3f3"}, {color: "#f435"} ], } */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM