简体   繁体   English

替换数组中每个对象的值

[英]replace value of each object inside array

I want to change the value of each objects inside the array.我想更改数组中每个对象的值。 I want to do a path.parse(name).name on the name object inside of the item array and return this array with the new values我想在item array内的name object上做一个path.parse(name).name并用新值返回这个array

My array is like this :我的数组是这样的:

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

here is my code :这是我的代码:

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

The output i want is :我想要的输出是:

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

This will give you your desired output这会给你你想要的输出

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 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM