如何在Javascript中创建对象内的数组列表

7 浏览
0 Comments

如何在Javascript中创建对象内的数组列表

我从数据库中得到的结果集如下:

{

"scrapped_name": [

"harry mccracken"

],

"publications": [

{

"_id": "5d3021a6eedfed29a7b5ae75",

"name": "Fast Company"

},

{

"_id": "5d3021a6eedfed1728b5ae7c",

"name": null

}

],

"language": [],

"location": [],

"_id": "5d3021a6eedfed37d3b5ae88",

"name": "harry mccracken",

"createdAt": "2019-07-18T07:37:10.626Z",

"updatedAt": "2019-07-18T07:37:10.626Z",

"social_media": []

}

1)我需要对结果数据集执行一些操作,然后需要手动使结果集与上述相同。在制作对象内部的Publication数组时,我遇到了问题。

2)有人可以帮我在结果集中添加新的键值吗?就像我从数据库查询中获得的上述结果一样,现在我想推入新的键值:

publisher : true

所以我在第二个问题中想要的结果数组是:

{

"scrapped_name": [

"harry mccracken"

],

"publications": [

{

"_id": "5d3021a6eedfed29a7b5ae75",

"is_followed": true,

"name": "Fast Company"

},

{

"_id": "5d3021a6eedfed1728b5ae7c",

"is_followed": false,

"name": null

}

],

"language": [],

"location": [],

"_id": "5d3021a6eedfed37d3b5ae88",

"name": "harry mccracken",

"createdAt": "2019-07-18T07:37:10.626Z",

"updatedAt": "2019-07-18T07:37:10.626Z",

"social_media": [],

"publisher": true

}

上述的"is_followed"将在运行时根据其他表动态计算。

0
0 Comments

问题原因:object.publisher = true;语句没有成功将值添加到对象中。

解决方法:检查代码后发现,问题可能是因为object对象中没有初始化publisher属性,所以无法直接给它赋值。解决方法是在对象初始化时,给对象添加一个空的publisher属性,然后再赋值为true。

以下是修改后的代码:

const object = {
  scrapped_name: [
    'harry mccracken',
  ],
  publications: [
    {
    _id: '5d3021a6eedfed29a7b5ae75',
    name: 'Fast Company',
    },
    {
    _id: '5d3021a6eedfed1728b5ae7c',
    name: null,
    },
  ],
  language: [],
  location: [],
  _id: '5d3021a6eedfed37d3b5ae88',
  name: 'harry mccracken',
  createdAt: '2019-07-18T07:37:10.626Z',
  updatedAt: '2019-07-18T07:37:10.626Z',
  social_media: [],
  publisher: null, // Initialize publisher property with null
};
object.publisher = true; // Assign the value true to publisher property
// Customise `publications` array
if (object.publications && Array.isArray(object.publications)) {
  object.publications.forEach((f) => {
    const referenceObj = f;
    let hasFollow = false;
    if (f._id && f._id === '5d3021a6eedfed29a7b5ae75') {
      hasFollow = true;
    }
    referenceObj.is_followed = hasFollow;
  });
}
console.log(object);

请在chrome的控制台中尝试以下代码:

const obj = {};
obj.a = 'A';
console.log(obj);

输出结果将会是:

{a: "A"}

希望以上解决方法可以帮助您成功向对象中添加值。

0