简体   繁体   English

如何将对象数组添加到现有对象

[英]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 我有一个object ,我想将一个object array推入其中,这样它必须看起来像这样

What i'm trying to push is skills object skills = {"css":true,"javascript":true} 我要推动的是技能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. 代替一个空对象,为对象提供skills属性作为第一个参数,并在其中添加skills对象(如果您不想保留对原始对象的引用,则添加其副本)作为第一个元素。

 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 在Object.assign()内部将创建领域技能并将其值添加到数组中

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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