插入/删除嵌套JavaScript对象中的数据

时间:2017-02-07 11:39:33

标签: javascript json reactjs

我正在使用react.js来管理嵌套的“项目”列表。我的对象看起来像这样:

const items = [
  {
    _id: 0,
    content: 'Item 1 something',
    note: 'Some note for item 1'
  },
  {
    _id: 5,
    content: 'Item 1.1 something',
    note: 'Some note for item 1.1'
  },
  {
    _id: 1,
    content: 'Item 2 something',
    note: 'Some note for item 2',
    subItems: [
      {
        _id: 2,
        parent_id: 1,
        content: 'Sub Item 1 something',
        subItems: [{
          _id: 3,
          parent_id: 2,
          content: 'Sub Sub Item 4'
        }]
      }
    ]
  }
];

如果我只有任何项目的_id。如何在任何级别(顶级或嵌套)的项目之前/之后插入另一个项目,并删除任何级别的项目,前提是我只有_id。

由于我正在使用react.js,我该如何以不可变的方式进行这些操作?

1 个答案:

答案 0 :(得分:1)

您可以为此创建递归函数。首先你可以使用JSON parse/stringify克隆你的数组,这不是最好的方法,但在这种情况下可以工作,然后你可以使用for...in循环来循环数据,如果在某个对象中找到id,它将添加新项目使用unshift到该数组的开头。

const items = [{"_id":0,"content":"Item 1 something","note":"Some note for item 1"},{"_id":5,"content":"Item 1.1 something","note":"Some note for item 1.1"},{"_id":1,"content":"Item 2 something","note":"Some note for item 2","subItems":[{"_id":2,"parent_id":1,"content":"Sub Item 1 something","subItems":[{"_id":3,"parent_id":2,"content":"Sub Sub Item 4"}]}]}]  

function addItem(data, item, id) {
  data = JSON.parse(JSON.stringify(data))

  function inner(data, item, id, parent) {
    for (var i in data) {
      if (data[i]._id == id) {
        parent.unshift(item)
        return;
      }
      if (data[i] && data[i].hasOwnProperty('subItems')) {
        inner(data[i].subItems, item, id, data[i].subItems)
      }
    }
  }
  inner(data, item, id, data)
  return data;
}

var newItem = {
  name: 'Lorem',
  age: 20
}
console.log(addItem(items, newItem, 3))

如果您要删除而不是添加项目,可以使用splice(i, 1)

const items = [{"_id":0,"content":"Item 1 something","note":"Some note for item 1"},{"_id":5,"content":"Item 1.1 something","note":"Some note for item 1.1"},{"_id":1,"content":"Item 2 something","note":"Some note for item 2","subItems":[{"_id":2,"parent_id":1,"content":"Sub Item 1 something","subItems":[{"_id":3,"parent_id":2,"content":"Sub Sub Item 4"}]}]}]  


function addItem(data, item, id) {
  data = JSON.parse(JSON.stringify(data))

  function inner(data, item, id, parent) {
    for (var i in data) {
      if (data[i]._id == id) {
        data.splice(i, 1)
        return
      }
      if (data[i] && data[i].hasOwnProperty('subItems')) {
        inner(data[i].subItems, item, id, data[i].subItems)
      }
    }
  }
  inner(data, item, id, data)
  return data;
}

console.log(addItem(items, '', 2))

相关问题