Reputation: 55
I have 2 Objects.
Object1:
{
"a": "XXXXX",
"b": "YYYYY",
"c": "ZZZZZ"
}
and Object2:
{
"a": "KKKKK",
"b": "LLLLL",
"c": "MMMMM"
}
both have the same length and same keys at the same index, but different values.
Result should be:
{
"XXXXX": "KKKKK",
"YYYYY": "LLLLL",
"ZZZZZ": "MMMMM"
}
i've tried:
for (let el in Object2){
el = Object1[el]
}
but its not working. What i'm doing wrong?
Upvotes: 1
Views: 134
Reputation: 35222
You can loop through the keys and set the key and value of the output object based on the value in the input objects
const o1 = { a: "XXXXX", b: "YYYYY", c: "ZZZZZ" },
o2 = { a: "KKKKK", b: "LLLLL", c: "MMMMM" },
output = {};
for (let key in o1)
output[o1[key]] = o2[key]
console.log(output)
Upvotes: 0
Reputation: 3721
you can use Object.Values
+ reduce
something like this:
const a = {
"a": "XXXXX",
"b": "YYYYY",
"c": "ZZZZZ"
}
const b = {
"a": "KKKKK",
"b": "LLLLL",
"c": "MMMMM"
}
var res = Object.values(a).reduce((newObject, value, index) => {
newObject[value] = Object.values(b)[index]
return newObject;
}, {});
console.log(res)
Upvotes: 0
Reputation: 16908
We can use Array.prototype.reduce
and Object.entries
to iterate over the keys of the first object and use its values as the keys for the result
object:
const obj1 = {
"a": "XXXXX",
"b": "YYYYY",
"c": "ZZZZZ"
}
const obj2 = {
"a": "KKKKK",
"b": "LLLLL",
"c": "MMMMM"
}
const result = Object.entries(obj1).reduce((acc, ele) => {
acc[ele[1]] = obj2[ele[0]];
return acc;
}, {});
console.log(result);
Upvotes: 0
Reputation: 22776
You can also use Object.assign
with Object.values
:
var obj1 = {
"a": "XXXXX",
"b": "YYYYY",
"c": "ZZZZZ"
};
var obj2 = {
"a": "KKKKK",
"b": "LLLLL",
"c": "MMMMM"
};
var obj3 = Object.assign(...Object.values(obj1).map((k, i) => ({[k]: Object.values(obj2)[i]})));
console.log(obj3);
Or, use a forEach
:
var obj1 = {
"a": "XXXXX",
"b": "YYYYY",
"c": "ZZZZZ"
};
var obj2 = {
"a": "KKKKK",
"b": "LLLLL",
"c": "MMMMM"
};
var obj3 = {};
Object.values(obj1).forEach((key, i) => obj3[key] = Object.values(obj2)[i]);
console.log(obj3);
Upvotes: 0
Reputation: 16908
We can use Array.prototype.reduce
and Object.keys
to iterate over the keys of the first object and use its values as the keys for the result
object:
const obj1 = {
"a": "XXXXX",
"b": "YYYYY",
"c": "ZZZZZ"
}
const obj2 = {
"a": "KKKKK",
"b": "LLLLL",
"c": "MMMMM"
}
const result = Object.keys(obj1).reduce((acc, ele, idx) => {
acc[obj1[ele]] = obj2[ele];
return acc;
}, {});
console.log(result);
Upvotes: 0
Reputation: 951
const x = {
"a": "XXXXX",
"b": "YYYYY",
"c": "ZZZZZ"
}
const y = {
"a": "KKKKK",
"b": "LLLLL",
"c": "MMMMM"
}
const z = Object.keys(x).reduce((acc, key) => {
acc[x[key]] = y[key]
return acc
},{})
console.log(z)
Upvotes: 2