繁体   English   中英

推一个 object 多维数组 object javascript

[英]Push an object multidimension array object javascript

请帮我。 当我想将 object 推入现有阵列 object 时,我遇到了问题。 请告诉我是否有类似的问题。

这是我的代码:

var menu = [{
  "id": 1,
  "text": "menu 1",
  "parent": "-",
  "child": {}
},
{
  "id": 3,
  "text": "menu 3",
  "parent": "-",
  "child": {}
}];

var menuchild = [{
  "id": 2,
  "parent": 1,
  "text": "menu 2"
},
{
  "id": 5,
  "parent": 3,
  "text": "menu 5"
},
{
  "id": 6,
  "parent": 1,
  "text": "menu 6"
}];

$.each(menuchild, function(key, value) {

  let item = {
    'id': value.id,
    'text': value.text,
    'parent': value.parent
  }

let parentindex = menu.findIndex(el => el.id === value.parent);

// if i use this return error push is not a function
menu[parentindex]['child'].push(item) 

// if i use this the data wil be replace if there is 2 object with same parent
menu[parentindex]['child'] = item

})

请告诉我推送数据的最佳方式是什么?

如果您希望menuchild项是object ,那么下面就是方法。

 var menu = [ { id: 1, text: 'menu 1', parent: '-', child: {}, }, { id: 3, text: 'menu 3', parent: '-', child: {}, }, ]; var menuchild = [ { id: 2, parent: 1, text: 'menu 2', }, { id: 5, parent: 3, text: 'menu 5', }, { id: 6, parent: 1, text: 'menu 6', }, ]; let updatedParents = menuchild.map(ch => { childParent = menu.find(m => m.id === ch.parent) return {...childParent, child: {...ch} } }); console.log(updatedParents)
 .as-console-wrapper{ max-height: 100%;important; }

但是,如果希望menu数组的child元素是array ,那么下面是实现您正在寻找的 output 的方法。

 var menu = [{ id: 1, text: 'menu 1', parent: '-', child: [], }, { id: 3, text: 'menu 3', parent: '-', child: [], }, ]; var menuchild = [{ id: 2, parent: 1, text: 'menu 2', }, { id: 5, parent: 3, text: 'menu 5', }, { id: 6, parent: 1, text: 'menu 6', }, ]; const finalResult = menuchild.reduce((result, ch) => { let index = result.findIndex(r => r.id === ch.parent); result[index].child.push(ch); return result; }, [...menu]) console.log(finalResult)
 .as-console-wrapper{ max-height: 100%;important; }

暂无
暂无

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

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