【问题标题】:How to make Array List inside Object Javascript [duplicate]如何在对象Javascript中制作数组列表[重复]
【发布时间】:2019-08-26 09:25:35
【问题描述】:

我将 DB 中的结果集设置为

{
    "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
}

上面的会在运行时从其他表中动态计算出来。

【问题讨论】:

  • 循环遍历publications数组并将is_followed添加到每个对象?
  • 数据['publisher'] = true

标签: javascript arrays object


【解决方案1】:

         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: [],
  };
  
  object.publisher = true; // Added a key `publisher`
  // 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);

【讨论】:

  • 我也在使用 object.publisher = true,但它没有将值添加到对象中。请帮我将值添加到对象。
  • 请在此处粘贴您的object
  • 在 chrome 的控制台试试这个 ``` const obj = {}; obj.a = 'A';控制台.log(obj); ```
猜你喜欢
  • 2015-09-16
  • 2020-03-11
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-13
  • 2015-03-09
  • 1970-01-01
相关资源
最近更新 更多