2

I have the data in this format

[{
    "Consumer": [{
        "Associated ID": "JSUDB2LXXX / BIC 7503 / US",
        "Parent Consumer": "7503"
    }],
    "Owner": [{
        "Entity": "EN",
        "Region": "LA"
    }]
}]

I want to convert in into the below format, I have to add title and value as the new key to the old key and value and have to separate each old key value in a separate object.

[{
    "Consumer": [{
            "title": "Associated ID",
            "name": "JSUDB2LXXX / BIC 7503 / US"
        },
        {
            "title": "Parent Consumer",
            "name": "7503"
        }
    ],
    "Owner": [{
            "title": "Entity",
            "name": "EN"
        },
        {
            "title": "Region",
            "name": "LA"
        }
    ]
}]

2 Answers 2

2

Hope it helps:

let data = [{
    "Consumer": [{
        "Associated ID": "JSUDB2LXXX / BIC 7503 / US",
        "Parent Consumer": "7503"
    }],
    "Owner": [{
        "Entity": "EN",
        "Region": "LA"
    }]
}]

let final = []
data.forEach(el => {
  Object.keys(el).forEach(key => {
    let values = []
    Object.entries(el[key][0]).forEach(entry => {
      values.push({title: entry[0], name: entry[1]})
    })
    let newElement = {}
    newElement[key] = values
    final.push(newElement)
  })
})
console.log(final)

You can try it here :

https://jsbin.com/wazuyoyidi/edit?js,console

Sign up to request clarification or add additional context in comments.

1 Comment

yes, it worked like a charm thank you. @MarcSanchez
0

Another aproach.

const results = data.map((firstLevel) => {
  const finalObject = {};
  Object.entries(firstLevel).forEach(([name, array]) => {
    finalObject[name] = array
      .map((obj) =>
        Object.entries(obj).map(([title, name]) => ({ title, name }))
      )
      .flat();
  });
  return finalObject;
});

[https://jsbin.com/rafinobexa/edit?js,console][1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.