简体   繁体   English

如何在javascript /打字稿中重新映射json键值映射?

[英]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. 在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. 我正在尝试更改响应以使其适合API请求。

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 我想要实现的是摆脱json文件中的第一级密钥,因为我发送给它的API没有这些密钥,它只使用第二级中的密钥

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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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