I have two objects, that contains same number of properties:
object1: {
prop1: 'data12',
prop2: 'data13',
prop3: 'data58',
prop4: 'xyz',
// more props here...
}
object2: {
prop1: 123,
prop2: '[email protected]',
prop3: 'text',
prop4: 'bla',
// more props here...
}
I want to build an array {name: '', value: ''}
based on this objects:
[
{ data12: 123 },
{ data13: '[email protected]' },
{ data58: text },
{ xyz: 'bla' },
]
How can you do that? The number of properties could be different.
CodePudding user response:
Just using Object.keys()
can do it
let object1 = {
prop1: 'data12',
prop2: 'data13',
prop3: 'data58',
prop4: 'xyz',
}
let object2 = {
prop1: '123',
prop2: '[email protected]',
prop3: 'text',
prop4: 'bla',
}
let result =[]
let obj = {}
Object.keys(object1).forEach(k =>{
obj[object1[k]] = object2[k]
})
result.push(obj)
// combined with reduce can also do it
/*
let obj =Object.keys(object1).reduce((a,c) => {
a[object1[c]] = object2[c]
return a
},{})
*/
result.push(obj)
console.log(result)