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

时间:2017-09-19 10:14:41

标签: javascript jquery

我有一个object,我想将array object推入其中,以便它看起来像这样

我想要推动的是技能object skills = {"css":true,"javascript":true}

我想要像下面的对象

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

我正在尝试这样的事情



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




3 个答案:

答案 0 :(得分:0)

而不是一个空对象提供一个具有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);




答案 1 :(得分:0)

你可以做到



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]}
Object.assign()内部的

将创建字段技能并在其中添加数组中的值

答案 2 :(得分:0)

你可以做以下代码。

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