替换数组内每个对象的值

时间:2019-03-09 14:09:15

标签: javascript json

我想更改数组内每个对象的值。我想在path.parse(name).name内的name object上做一个item array,并用新值

返回此array

我的数组是这样的:

[
  {
    "name": "core Test",
    "item": [
      {
        "name": "test/core/core.js",
        "item": []
      }
    ]
  },
  {
    "name": "users Test",
    "item": [
      {
        "name": "test/users/user.js",
        "item": []
      }
    ]
  }
]

这是我的代码:

array.forEach((element) => {
  const { item } = element;
  item.forEach((i) => {
    const { name } = i;
    const newname = path.parse(name).name;
    console.log(newname);
  });
});

我想要的输出是:

[
  {
    "name": "core Test",
    "item": [
      {
        "name": "core",
        "item": []
      }
    ]
  },
  {
    "name": "users Test",
    "item": [
      {
        "name": "user",
        "item": []
      }
    ]
  }
]

1 个答案:

答案 0 :(得分:2)

这将为您提供所需的输出

const path = require('path')

const datas = [
  {
    name: 'core Test',
    item: [
      {
        name: 'test/core/core.js',
        item: []
      }
    ]
  },
  {
    name: 'users Test',
    item: [
      {
        name: 'test/users/user.js',
        item: []
      }
    ]
  }
]

const transformedData = datas.map(data => {
  data.item = data.item.map(x => ({
    name: path.parse(x.name).name,
    item: x.item
  }))
  return data
})

console.log(transformedData )