Home > OS >  Merging object key into new object key - Javascript
Merging object key into new object key - Javascript

Time:03-06

Hello i have JSON like this one, an array then object inside them

[
    {
        "namaBagian": "Bagian1",
        "bagianID": 1,
        "postID": [
            1,
            2,
            3
        ],
        "judul": [
            "Tes",
            "a",
            "TesFront"
        ]
    },
    {
        "namaBagian": "Bagian2",
        "bagianID": 2,
        "postID": [
            4,
            5
        ],
        "judul": [
            "Testing",
            ""
        ]
    },
]

I want to merge "postID" and "judul" into one new object key. I need help how to make like below :

[
    {
        "namaBagian": "Bagian1",
        "bagianID": 1,
        "newKey": {
          "postID": [
            1,
            2,
            3
          ],        
          "judul": [
            "Tes",
            "a",
            "TesFront"
          ]
        },
    },
    {
        "namaBagian": "Bagian2",
        "bagianID": 2,
        "newKey":{
        "postID": [
            4,
            5
        ],
        "judul": [
            "Testing",
            ""
        ]
}
    },
]

I Have problem when i want to make new object keys with value from merging from 2 object key before. I'm very happy when someone can help me to solve this. i need help from javascript code

CodePudding user response:

Simplify the problem being presented. You effectively want to turn an array of this object:

{
  "prop1": "val",
  "prop2": "val2"
}

Into an array of this object:

{
  "newprop": {
    "prop1": "val1",
    "prop2": "val2"
  }
}

You can project an array into a new shape with .map. For example:

var newArr = arr.map(x => {
  return {
    newprop: {
      prop1: x.prop1,
      prop2: x.prop2
    }
  }
});

So yours might look something like this:

var newArr = arr.map(x => {
  return {
    namaBagian: x.namaBagian,
    bagianID: x.bagianID,
    newKey: {
      postID: x.postID,
      judul: x.judul
    }
  }
});

If the shape of the objects is more dynamic, you could potentially make clever use of the spread operator to not have to specify every value explicitly. But the general principle is the same. What you're looking to do is map an array into a new array, where each element takes on a new shape built from the data on the existing element.

  • Related