首页 > javascript > 推入数组的第一个对象

推入数组的第一个对象 (Push into the first object of an array)

2019-03-07 javascriptarrays

问题

我想将对象的对象推入数组的第一个对象。这是我的代码:

const titles = {
  name: 'Not 1',
  name2: 'Not 2',
};

const array = [{ type: 'type', titles: [] }];
let e;
for (const name in titles) {
  e = titles[name];
}
array.push({ name: e });

这是我得到的结果:

[
  { 
    "type": "type", 
    "titles": [] 
  }, 
  { "name": "Not 2" }
]

这是我想要的结果:

[
  { 
    "type": "type", 
    "titles": [
      { "name": "Not 1" },
      { "name": "Not 2" }
    ] 
  }
]

解决方法

访问对象并使用push push推送数组中的其他对象

const titles = {
  name: 'Not 1',
  name2: 'Not 2',
};

const array = [{
  type: 'type',
  titles: []
}, {
  type: 'type',
  titles: []
}];
let e;
for (const name in titles) {
  e = titles[name];
  array.forEach(x => x.titles.push({
    name: e
  }))

}

console.log(array)


问题

I want to push an object of object into the first object of an array. Here is my code:

const titles = {
  name: 'Not 1',
  name2: 'Not 2',
};

const array = [{ type: 'type', titles: [] }];
let e;
for (const name in titles) {
  e = titles[name];
}
array.push({ name: e });

This is the result i get :

[
  { 
    "type": "type", 
    "titles": [] 
  }, 
  { "name": "Not 2" }
]

This is the result i want :

[
  { 
    "type": "type", 
    "titles": [
      { "name": "Not 1" },
      { "name": "Not 2" }
    ] 
  }
]

解决方法

Access the object and using push push the other object in the array

const titles = {
  name: 'Not 1',
  name2: 'Not 2',
};

const array = [{
  type: 'type',
  titles: []
}, {
  type: 'type',
  titles: []
}];
let e;
for (const name in titles) {
  e = titles[name];
  array.forEach(x => x.titles.push({
    name: e
  }))

}

console.log(array)

相似信息