简体   繁体   中英

how to add array of objects into existing object

I have an object , I want to push an array of object into it so that it must look like this

What i'm trying to push is skills object skills = {"css":true,"javascript":true}

I want something like below object

alldata = {"companyName":"abc","jobRole":"permanent",skills:[{"css":true,"javascript":true}]};

I'm trying something like this

 var details = { companyName: "", jobRole: "", startDate: "2017-09-19T09:59:06.479Z", endDate: "2017-09-19T09:59:06.479Z", html: "html" }; var skills = { html: "html", css: "css", javascript: "javascript", php: "php", laravel: "" }; const allData = Object.assign({}, details, skills); console.log(allData); 

Instead of an empty object provide an object with skills property as the first argument, where add skills object(or its clone in case you don't want to keep the reference to the original object) as the first element.

 var details = {companyName: "", jobRole: "", startDate: "2017-09-19T09:59:06.479Z", endDate: "2017-09-19T09:59:06.479Z", html: "html"}; var skills = {html: "html", css: "css", javascript: "javascript", php: "php", laravel: ""}; const allData = Object.assign({ skills: [skills] }, details); // or in case you don't want to keep reference to main object const allData1 = Object.assign({ skills: [Object.assign({},skills)]}, details); console.log(allData); console.log(allData1); 

you can do

 var details = {companyName: "", jobRole: "", startDate: "2017-09-19T09:59:06.479Z", endDate: "2017-09-19T09:59:06.479Z", html: "html"}; var skills = {html: "html", css: "css", javascript: "javascript", php: "php", laravel: ""}; const allData = Object.assign({}, details, {skills : [skills]}); console.log(allData); 

{skills : [skills]}

inside Object.assign() would create the field skills and add to it the value in an array

you can do following code.

    var details = {companyName: "", jobRole: "", startDate: "2017-09-
    19T09:59:06.479Z", endDate: "2017-09-19T09:59:06.479Z", html: 
    "html",skills:[]};

    var skills = {html: "html", css: "css", javascript: "javascript", 
    php:"php", laravel: ""};

    details["skills"].push(skills);

    console.log(details);

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