'JavaScript, map object in other object with possition
I need to create an object like this:
const needThis = {
0: {
LABEL: {
A: 1,
B: 2
}
},
1: {
OTHER_LABEL: {
E: 1,
B: 4
}
},
// etc..., more objects with first key 3, 4, and so on
}
The data that I have is this:
const haveThis = {
LABEL: {
A: 1,
B: 2
},
OTHER_LABEL: {
E: 1,
B: 4
}
}
In other words, I have to create an object but putting as a key of each object the position of the haveThis object.
Here I'm trying:
const needThis = {
0: {
LABEL: {
A: 1,
B: 2
}
},
1: {
OTHER_LABEL: {
E: 1,
B: 4
}
}
}
const haveThis = {
LABEL: {
A: 1,
B: 2
},
OTHER_LABEL: {
E: 1,
B: 4
}
}
const result = {}
const keys = Object.keys(haveThis)
const values = Object.values(haveThis)
keys.forEach((key, i) => {
const inside = {}
inside[keys[i]] = values[i]
result[i] = inside
})
console.log(result)
Solution 1:[1]
By modifying your code and using computed property names, this can be done like this:
const needThis = {
0: {
LABEL: {
A: 1,
B: 2
}
},
1: {
OTHER_LABEL: {
E: 1,
B: 4
}
}
}
const haveThis = {
LABEL: {
A: 1,
B: 2
},
OTHER_LABEL: {
E: 1,
B: 4
}
}
const result = {}
const keys = Object.keys(haveThis)
//const values = Object.values(haveThis) // No need for this
keys.forEach((key, i) => {
result[i] = { [key] : haveThis[key] };
})
console.log(result)
You can skip the Object.values(), if you simple want to use the keys from haveThis.
Also, you can use Object.entries() directly too/
const needThis = {
0: {
LABEL: {
A: 1,
B: 2
}
},
1: {
OTHER_LABEL: {
E: 1,
B: 4
}
}
}
const haveThis = {
LABEL: {
A: 1,
B: 2
},
OTHER_LABEL: {
E: 1,
B: 4
}
}
const result = {}
const entries = Object.entries(haveThis)
//const values = Object.values(haveThis) // No need for this
entries.forEach(([key, value],index) => {
result[index] = { [key] : value };
});
console.log(result);
Solution 2:[2]
const wrapKeyValuePair = (keyValuePair, index) => ([ index, { [keyValuePair[0]]: keyValuePair[1] } ]);
const getKeyValuePairs = (obj) => Object.entries(obj).map(wrapKeyValuePair);
Object.fromEntries(getKeyValuePairs(haveThis));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tushar Shahi |
| Solution 2 | KobraKalle |
