将新对象推送到嵌套对象

时间:2019-11-20 12:02:47

标签: javascript arrays

我正在尝试用angular8制作问卷。
有一个带有加号按钮的动态表格。您可以通过单击加号按钮添加新字段,该字段应添加到所选字段的下方。为此,我试图使嵌套的json对象 我想在特定对象之后再添加一个对象。
例如-我需要在ID为3的对象之后添加新对象

  

这是我到目前为止所做的

mainConatiners = [
           {
               page_title : "This is first page.",
               "data":[
                   {
                       id:1,
                       title:"This is first question",
                       type:1,
                       page:0,
                       position:'0',
                       parent:'0'
                   },
                   {
                       id:2,
                       title:"This is second question",
                       type:2,
                       page:0,
                       position:'1',
                       parent:0,
                       "data":[
                           {
                               key:"[data][1][data][0]",
                               id:3,
                               title:"This is third question",
                               type:1,
                               page:0,
                               position:'1-0',
                               parent:2
                           },
                           {
                               id:4,
                               title:"This is fourth question",
                               type:2,
                               page:0,
                               position:'1-1',
                               parent:2,
                               "data":[
                                   {
                                       id:5,
                                       title:"This is tenth question",
                                       type:2,
                                       page:0,
                                       position:'1-1-0',
                                       parent:'2-4'
                                   }
                               ]
                           }
                       ]
                   }
               ]
           }]

  

预期输出-

mainConatiners = [
           {
               page_title : "This is first page.",
               "data":[
                   {
                       id:1,
                       title:"This is first question",
                       type:1,
                       page:0,
                       position:'0',
                       parent:'0'
                   },
                   {
                       id:2,
                       title:"This is second question",
                       type:2,
                       page:0,
                       position:'1',
                       parent:0,
                       "data":[
                           {
                               key:"[data][1][data][0]",
                               id:3,
                               title:"This is third question",
                               type:1,
                               page:0,
                               position:'1-0',
                               parent:2
                           },
                           {
                               key:"[data][1][data][0]",
                               id:12,
                               title:"This is third question",
                               type:1,
                               page:0,
                               position:'1-0',
                               parent:2
                           },
                           {
                               id:4,
                               title:"This is fourth question",
                               type:2,
                               page:0,
                               position:'1-1',
                               parent:2,
                               "data":[
                                   {
                                       id:5,
                                       title:"This is tenth question",
                                       type:2,
                                       page:0,
                                       position:'1-1-0',
                                       parent:'2-4'
                                   }
                               ]
                           }
                       ]
                   }
               ]
           }]

4 个答案:

答案 0 :(得分:2)

这是可变的解决方案-我们首先将所有对象索引到idHash映射,该映射包含有关对象ID,数据数组中的对象索引以及dara数组本身(parentArr)的信息-然后我们找到十个对象id = 3并在其后声明new

let idHash = {} // id=> hash object (hash obiect= {obj,index,parentArr)}
let makeHash = data => (data||[]).forEach((d,i)=> 
      (idHash[d.id]={ obj:d, index:i, parentArr: data}, makeHash(d.data)));

makeHash(mainConatiners);

let hobj = idHash[3] // hash object with object id=3 after which we want to insert
hobj.parentArr.splice(hobj.index+1,0,newObj);

mainConatiners = [{
  page_title: "This is first page.",
  "data": [{
      id: 1,
      title: "This is first question",
      type: 1,
      page: 0,
      position: '0',
      parent: '0'
    },
    {
      id: 2,
      title: "This is second question",
      type: 2,
      page: 0,
      position: '1',
      parent: 0,
      "data": [{
          key: "[data][1][data][0]",
          id: 3,
          title: "This is third question",
          type: 1,
          page: 0,
          position: '1-0',
          parent: 2
        },
        {
          id: 4,
          title: "This is fourth question",
          type: 2,
          page: 0,
          position: '1-1',
          parent: 2,
          "data": [{
            id: 5,
            title: "This is tenth question",
            type: 2,
            page: 0,
            position: '1-1-0',
            parent: '2-4'
          }]
        }
      ]
    }
  ]
}]

let newObj = {
  key: "[data][1][data][0]",
  id: 12,
  title: "This is third question",
  type: 1,
  page: 0,
  position: '1-0',
  parent: 2
}

let idHash = {} // id=> hash object (hash obiect= {obj,index,parentArr)}
let makeHash = data => (data||[]).forEach((d,i)=> 
      (idHash[d.id]={ obj:d, index:i, parentArr: data}, makeHash(d.data)));

makeHash(mainConatiners);

let hobj = idHash[3] // hash object with object id=3 after which we want to insert
hobj.parentArr.splice(hobj.index+1,0,newObj);

console.log(mainConatiners)

答案 1 :(得分:1)

您可以递归遍历数组,并按如下所示插入对象


let mainContainers = [
  {
    page_title: 'This is first page.',
    data: [
      {
        id: 1,
        title: 'This is first question',
        type: 1,
        page: 0,
        position: '0',
        parent: '0'
      },
      {
        id: 2,
        title: 'This is second question',
        type: 2,
        page: 0,
        position: '1',
        parent: 0,
        data: [
          {
            key: '[data][1][data][0]',
            id: 3,
            title: 'This is third question',
            type: 1,
            page: 0,
            position: '1-0',
            parent: 2
          },
          {
            id: 4,
            title: 'This is fourth question',
            type: 2,
            page: 0,
            position: '1-1',
            parent: 2,
            data: [
              {
                id: 5,
                title: 'This is tenth question',
                type: 2,
                page: 0,
                position: '1-1-0',
                parent: '2-4'
              }
            ]
          }
        ]
      }
    ]
  }
];
let objectToInsert = {
  key: '[data][1][data][0]',
  id: 12,
  title: 'This is third question',
  type: 1,
  page: 0,
  position: '1-0',
  parent: 2
};
/**
 * 
 * @param {Array<any>} mainContainer Array of data
 * @param {any} idTobeMatched id to be matched
 * @param {any} newObject Object to be inserted
 * @returns modified array 
 */

let addNewObject = (mainContainer, idTobeMatched, newObject) => {
  for (let i = 0; i < mainContainer.length; i++) {
    if (mainContainer[i].id == idTobeMatched) {
      let indexOfNewObject = i + 1;
      mainContainer.splice(indexOfNewObject, 0, newObject);
      return mainContainer;
    } else if (mainContainer[i].data && mainContainer[i].data.length) {
      mainContainer[i].data = addNewObject(mainContainer[i].data, idTobeMatched, newObject);
    }
  }
  return mainContainer;
};
let expectedOutput = addNewObject(mainContainers, 3, objectToInsert);
console.log(JSON.stringify(expectedOutput, null, 2));

答案 2 :(得分:1)

您可以使用递归

    mainConatiners = [{
    page_title: "This is first page.",
    "data": [{
            id: 1,
            title: "This is first question",
            type: 1,
            page: 0,
            position: '0',
            parent: '0'
        },
        {
            id: 2,
            title: "This is second question",
            type: 2,
            page: 0,
            position: '1',
            parent: 0,
            "data": [{
                    key: "[data][1][data][0]",
                    id: 3,
                    title: "This is third question",
                    type: 1,
                    page: 0,
                    position: '1-0',
                    parent: 2
                },
                {
                    id: 4,
                    title: "This is fourth question",
                    type: 2,
                    page: 0,
                    position: '1-1',
                    parent: 2,
                    "data": [{
                        id: 5,
                        title: "This is tenth question",
                        type: 2,
                        page: 0,
                        position: '1-1-0',
                        parent: '2-4'
                    }]
                }
            ]
        }
    ]
}]

var globalFLag = true;

add2(mainConatiners, 3, {
    test: 0
})


console.log(JSON.stringify(mainConatiners))



function add2(arr, id, newObj) {
if(!globalFLag){
    return;
}
console.log({arr})

if(Array.isArray(arr.data)){
    arr = arr.data
}
for (let items of arr) {
    if (items.id == 3) {
        arr.push(newObj)
        console.log('pushed !!!!!!!!!!!!!!!!')
        console.log({mainConatiners:JSON.stringify(mainConatiners)})
        globalFLag = false;

        // process.exit()
        return;
        break;
    }else{
        console.log({items})
        if(items.data){
            for(let item of items.data){
                add2(items,id,newObj)
            } 
        }

    }
}

}

答案 3 :(得分:1)

尝试使用Depth First Search Algorithm

let arr = [
    {
        page_title : "This is first page.",
        "data":[
            {
                id:1,
                title:"This is first question1",
                type:1,
                page:0,
                position:'0',
                parent:'0'
            },
            {
                id:2,
                title:"This is second question2",
                type:2,
                page:0,
                position:'1',
                parent:0,
                "data":[
                    {
                        key:"[data][1][data][0]test",
                        id:3,
                        title:"This is third question3",
                        type:1,
                        page:0,
                        position:'1-0',
                        parent:2
                    },
                    {
                        id:4,
                        title:"This is fourth question4",
                        type:2,
                        page:0,
                        position:'1-1',
                        parent:2,
                        "data":[
                            {
                                id:5,
                                title:"This is tenth question5",
                                type:2,
                                page:0,
                                position:'1-1-0',
                                parent:'2-4'
                            }
                        ]
                    }
                ]
            }
        ]
    }];   


// Depth First Search Algorithm
function getParentNodeByChildrenKey(obj, targetId, paramKey) {
    if (obj.data) {
        if (obj.data.some(ch => ch.id == targetId))
            return obj;
        else {
            for (let item of obj.data) {
                if (item.data) {
                    let check = this.getParentNodeByChildrenKey(item, targetId, paramKey)
                    if (check) {
                        return check;
                    }
                }
            }
        }
    }
    return null
}

function test() {
    arr.forEach(a => {
        const desiredItems = getParentNodeByChildrenKey(a, '3', 'id');
        if (desiredItems && desiredItems.data)
            desiredItems.data.push({title: 'it is newly pushed'})
    })
    console.log(arr);

}

test();