0

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.

3
  • Is the properties appear in both object? Commented Nov 17, 2022 at 6:23
  • @lucumt yes, correct Commented Nov 17, 2022 at 6:24
  • So you can just my answer Commented Nov 17, 2022 at 6:25

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

what would be the best way to validate if the pops on obj1 and obj2 mismatch?
@sreginogemoh in my option,we need to iterate the properties and check if it appear on another object,maybe others have better solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.