Home > Enterprise >  new array with two objects with values from two objects with same key javascript
new array with two objects with values from two objects with same key javascript

Time:11-18

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

CodePudding user response:

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?

CodePudding user response:

There's probably a more efficient way but what I would do is : (assuming OBJ1 et OBJ2 have exactly the same keys)

OBJ3=[]
Object.keys(OBJ1).forEach((key)=>OBJ3[OBJ1[key]]=OBJ2[key])

For each key of OBJ1, adding a key,value to OBJ3 using OBJ value and OBJ2 value

CodePudding user response:

 const [list] = React.useState({
    keyNAME: 'lalala',
    toto: 'bbbb',
    tata: 'blablabla',
  });
  const [list2] = React.useState({ keyNAME: 18, toto: 7, tata: null });

  const newList = React.useMemo(() => {
    return Object.keys(list).map((key, index) => {
      return {
        string: list[key],
        value: list2[key],
      };
    });
  }, [list, list2]);

Demo

CodePudding user response:

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

  • Related