将线串推入对象数组

时间:2019-03-06 15:43:59

标签: javascript

我想将检索到的数据推入数组,但只推入第一个对象。

const arr = [{ name: 'name1', item: [] }, { name: 'name2', item: [] }];
routes.forEach((elementRoute) => {
  const { methods } = elementRoute;
  for (const m in methods) {
    let { title } = methods[m];
    arr[0].item.push({
      name: title,
      request: { method: m,},
    });
  }
});

我的路线数组是这样的:

[
  {
    methods: {
      get: {
        title: 'get users',
      },
    },
  }
];

它只推入item数组的第一个对象。这是我实际上想要得到的结果:

[
  {
    "name": "name1",
    "item": [
      { "name": "get users", "request": { "method": "get" } } }
    ]
  },
  {
    "name": "name2",
    "item": [
      { "name": "get users", "request": { "method": "get" } } }
    ]
  }
]

1 个答案:

答案 0 :(得分:2)

您还需要迭代arr才能填充所有项目。

const 
    arr = [{ name: 'name1', item: [] }, { name: 'name2', item: [] }],
    routes = [{ methods: { get: { title: 'get users' } } }, { methods: { get: { title: 'get user id' }, delete: {} } }, ];

arr.forEach(({ item }) =>
    routes.forEach(({ methods }) => {
        for (const method in methods) {
            let { title: name = 'Not specified' } = methods[method];
            item.push({ name, request: { method } });
        }
    })
);

console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }