js多维数组对每项对象修改、添加属性

//定义一个多维数组

  const arrs = [{

    id: 1, mc: "小明", childrens: [{ id: 11, mc: "小花", childrens: null }]

  },

  {

    id: 2, mc: "二明", childrens: [{ id: 12, mc: "二花", childrens: null }]

  },

  {

    id: 3, mc: "三明", childrens: [{ id: 13, mc: "三花", childrens: null }]

  }]

  //修改多维数组中的每个对象的mc和childrens属性名

  let lists = JSON.stringify(arrs);

  lists = lists.replace(/"mc"/g, '"title"');

  lists = lists.replace(/"childrens"/g, '"children"');

  const treeLists = JSON.parse(lists)

  //给多维数组中的每个对象添加属性key

  const addKey = arr => arr.map(item => ({

    ...item,

    key: item.id,//key值为当前项id

    children: item.children ? addKey(item.children) : [] // 这里要判断原数据有没有子级如果没有判断会报错

  }))

  const result = addKey(treeLists)

  console.log(result);

js多维数组对每项对象修改、添加属性_第1张图片

 输出结果展示

[{"id":1,"title":"小明","children":[{"id":11,"title":"小花","children":[],"key":11}],"key":1},{"id":2,"title":"二明","children":[{"id":12,"title":"二花","children":[],"key":12}],"key":2},{"id":3,"title":"三明","children":[{"id":13,"title":"三花","children":[],"key":13}],"key":3}]

js多维数组对每项对象修改、添加属性_第2张图片

此方法用到了正则与递归 

你可能感兴趣的:(javascript,前端)