Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

100
Views
Merging object key into new object key - Javascript

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

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.