将每个键具有多个值的对象转换为JS中的对象数组 [英] Convert an object with multiple values per key into array of objects in JS
问题描述
我有一个看起来像这样的对象:
I have an object that looks like this:
obj={"a": [1,2],"b": [3,4],"c": [5,6]}
我需要创建一个对象数组,其中每个对象都由每个键组成,每个键只有一个对应于其顺序的值,如下所示:
I need to create an array of objects where every object consists of each key with only one value corresponding to its order like this:
obj2=[{"a": 1, "b": 3, "c": 5},{"a": 2, "b": 4, "c": 6}]
此外,如果我使用JSON.stringify(obj)
使用JSON字符串,是否有可能直接从第一个字符串创建与JSON.stringify(obj2)
对应的字符串?
Also, if I have a JSON string using JSON.stringify(obj)
, would it be somehow possible to create string corresponding to JSON.stringify(obj2)
directly from the first one?
推荐答案
const obj = { "a": [1, 2], "b": [3, 4], "c": [5, 6] }
// create an array to store result
const result = []
// for each key in obj
Object.keys(obj).forEach(key => {
// for each array element of the property obj[key]
obj[key].forEach((value, index) => {
// if an object doesn't exists at the current index in result
// create it
if (!result[index]) {
result[index] = {}
}
// at the result index, set the key to the current value
result[index][key] = value
})
})
console.log(result)
这是我的算法,给出了预期的结果.
Here is my algorithm, given the expected result .
也可以说我有一个使用JSON.stringify(obj)的JSON字符串,是否有可能直接从第一个字符串创建与JSON.stringify(obj2)相对应的字符串?
Also, let's say i have a JSON string using JSON.stringify(obj), would it be somehow possible to create string corresponding to JSON.stringify(obj2) directly from the first one?
是的,您可以将.toJSON添加到obj:
Yes, you could add .toJSON to obj:
const obj = { "a": [1, 2], "b": [3, 4], "c": [5, 6] }
Object.setPrototypeOf(obj, {
toJSON: function () {
const result = []
Object.keys(this).forEach(key => {
this[key].forEach((value, index) => {
if (!result[index]) {
result[index] = {}
}
result[index][key] = value
})
})
return JSON.stringify(result);
}
})
console.log(JSON.stringify(obj))
您可以使用Object.setPrototypeOf,以便在Object.keys(obj).forEach迭代时,toJSON方法不被视为可枚举的键
You can use Object.setPrototypeOf so that toJSON method is not counted as an enumerable key when Object.keys(obj).forEach iterates
这篇关于将每个键具有多个值的对象转换为JS中的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!