Can jsonpath-plus move elements to child elements?

40 views Asked by At

What I have:

    [
     {"Name": "One",
      "ID": "1",
      "Child": [
        { "ChildName": "Alpha"},
         {"ChildName": "Beta"}
      ]
     },
     {"Name": "Two",
      "ID": "1",
      "Child": [
        { "ChildName": "Gamma"},
         {"ChildName": "Delta"}
      ]
     }
    ]

and what I'm looking for:

    [
      { "ChildName": "Alpha",
       "ID": "1"},
      { "ChildName": "Beta",
       "ID": "1"},
      { "ChildName": "Gamma",
       "ID": "2"},
      { "ChildName": "Delta",
       "ID": "2"}
    ]

Extensive searching gives 'you cant' or 'here is a JavaScript function'. But there must be an elegant way to solve this common data handling problem?

1

There are 1 answers

0
Serge On

try this

var newObj = [];
data.forEach((item) => {
  item.Child.forEach((ch) => {
    var obj = {};
    obj.ChildName = ch.ChildName;
    obj.ID = item.ID;
    newObj.push(obj);
  });
});

console.log(JSON.stringify(newObj));

result

[
{"ChildName":"Alpha","ID":"1"},
{"ChildName":"Beta","ID":"1"},
{"ChildName":"Gamma","ID":"2"},
{"ChildName":"Delta","ID":"2"}
]