简体   繁体   中英

How to remap json key-value mapping in javascript/ typescript?

Given

{"a": {"name": "king", "firstname": "Thomas"},"b": {"age": "21"}}

I´m trying to figure out a simple way converting it to

{"name": "king","firstname": "Thomas","age": "21"}

In Javascript/ Angular. Maybe someone has a goode idea, I would be very thankful. I´m trying to change a response to make it suitable for an API request.

Edit: I changed the question, I forgot to mention, that I have multiple key-values pairs in the second level.

What I´m trying to achieve is getting rid of the first level keys in a json-file because the API I´m sending it to doesn´t have those, it just uses the key in the second level

you could try something like:

const original = {"a": {"name": "thomas"},"b": {"age": "21"}}
const result = Object.values(original)

Or, if you need a bit more flexibility:

const original = {"a": {"name": "thomas"},"b": {"age": "21"}}
const result = []
Object.keys(original).forEach( key => result.push(original[key]) )

warm regards

This should work for you. I added a third property to the object to show you what happens if you have two objects with the same property (the one that is iterated later overwrites the one that comes before, but since you can't rely on property order in an object this could produce unexpected results). If none of your properties are duplicated then no worries.

 var data = {"a": {"name": "thomas"},"b": {"age": "21"},"c": {"age": "22"}}; // "c" will overwrite "b" var converted = Object.keys(data).reduce((o, e) => Object.assign(o, data[e]), {}); // Object.keys(data) gives the array [“a”, “b”, “c”] // Reduce that array to an object by assigning, to a new empty object, // the properties of the objects found in each property of data console.log(converted); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM