Article From:https://segmentfault.com/q/1010000011704236
Question:

Find the same ID delete object, and ID delete the same object.
var data =[{id:1,name:’Children: [{id: 2, name:’level two’, children: [{id: 3, name:’level one’, children: [{id: 31, name:’level two’}, {id: 32, name:’Two level, {id:33, name:’two, company_id:7}], company_id:8}], company_id:9}]
For example, ID==31, get the following array
[{id:1,name:’Children: [{id: 2, name:’level two’, children: [{id: 3, name:’level one’, children: [{id: 32, name:’level two’}, {id: 33, name:’Two level], company_id:7}], company_id:8}], company_id:9}]

Answer 0:
function filter (data, id) {
  var newData = data.filter(x => x.id !== id)
  newData.forEach(x => x.children && (x.children = filter(x.children, id)))
  return newData
}

Answer 1:

As shown in the following code:

var data = [{
  id: 1,
  name: 'At the first level,Children: [(]Id: 2,Name: 'two level',Children: [(]Id: 3,Name: 'level 1',Children: [(]Id: 31,Name: 'two level'}, {Id: 32,Name: 'two level'}, {Id: 33,Name: 'two level'Company_id: 7Company_id: 8]], company_id: 9]]]Function filter (arr, ID) {For (VaR I = 0; I < arr.length; i++) {Var El = arr[i]If (el.id = = = ID) {Arr.splice (I, 1)} else {If (el.children & & el.ch)Ildren.length) {Filter (el.children, ID)}}}Return arr}Filter (data, 31)

Answer 2:

Look at your data format is not very clear, it is recommended to format the code.

var data = [{
    id: 1,
    name: 'At the first level,Children: [(]Id: 2,Name: 'two level',Children: [(]Id: 3,Name: 'level 1',Children: [(]Id: 31,Name: 'two level'},{Id: 32,Name: 'two level'},{Id: 33,Name: 'two level']],Company_id: 7]],Company_id: 8]],Company_id: 9]]]

After formatting, as mentioned above.
The main idea is recursive function.

  1. filter(data,31)First go through the first level array, if the incoming parameter 31 is checked with the first level.idThe same is deleted directly; if not, continue traversing.
  2. If there is achildren,Continue to traverse thischildrenArray, perform recursive operation.filter(item.children,31),Continue to take the first step, always judging until nochildren,LastreturnNew processeddataobject

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *