VicWentBananas
VicWentBananas

Reputation: 5

new array with two objects with values from two objects with same key javascript

been trying for a while something i want to do:

i have two different objects with same keyName and different values, i need to create a new array that will contain a new object with two entries, the values from the two objects with same key.

enter code here
OBJ1{ keyNAME : 'lalala', toto: 'bbbb', tata: 'blablabla' }

OBJ2{ keyNAME : 18, toto: 7, tata: null }

// here something that i imagine could look similar to:
    
let newObjectKeys =  ['title', 'value' ] 
    
function createMyNewArray()=> {

     let newArray = []
     Use somehow OBJ1 and OBJ2, check the keys and create new array using 
     newObjectKeys
     i think it might use Object.keys method but all i have tried i don't get to the 
     result i need so i'm defo missing something 
} 


return newArray; 

console.log("new Array", newArray)

OUTPUT WOULD LOOK LIKE:

const newArray =[
   {
     string: "lalala",
     value: 18
   },
   {
     string: 'bbbb', 
     value: 7, 
   },
   {
     string: 'blablabla'
     value: null
   }, 
   
   ....
   ];

and so then i can use it on my front side like this:


{newArray.map((item)=> return(
<div>
p {item.string}
p {item.value}
</div>

))}

thank you

Upvotes: 0

Views: 984

Answers (2)

Smytt
Smytt

Reputation: 364

OBJ1 = { key: 'lalala', toto: 'bbbb', tata: 'blablabla' }

OBJ2 = { key: 18, toto: 7, tata: null }

const createArray = (obj1, obj2) =>
  Object.keys(obj1).map(key => ({
    string: obj1[key],
    value: obj2[key]
  }))

console.log(createArray(OBJ1, OBJ2))

Is this what you seek to do? Since you know for sure that both your objects are built with the same properties, we can create an array with the properties only - with Object.keys(). Then, we can traverse the array with the "map" method of Array to swap each key for the desired object by picking each corresponding value from each object.

Upvotes: 1

Azzy
Azzy

Reputation: 1731

Hope this helps

const OBJ1 = { keyNAME: "lalala", toto: "bbbb", tata: "blablabla" };

const OBJ2 = { keyNAME: 18, toto: 7, tata: null };

const createMyNewArray = (obj1, obj2) => {
  let newArray = [];

  for (const key in obj1) {
    if (key in obj2) {
      newArray.push({
        string: key,
        value: obj2[key]
      });
    }
  }
  return newArray;
};

const transformed = createMyNewArray(OBJ1, OBJ2);

console.log(transformed);

Sandbox example

Upvotes: 0

Related Questions