Home > Net >  In react and javascript, how can i map this objects key values correctly?
In react and javascript, how can i map this objects key values correctly?

Time:10-15

I have an object where each key is a unique id, and that keys value is an array of objects.

I have a prop, lets call it 'objId' whos value is one of the unique ids on the object

I want to map the array on the object where its key matches the prop 'objId'

To give a better visual example:

const bigObj = {
  a123: [{status: 'happy'}, {status: 'moody'}]
  a456: [{status: 'fail'}, {status: 'blah'}]
}

const objId = 'a123'

I want to map bigObj.a123 into my component because that matches the objId prop.

I'm kinda stuck and any ideas would help, can provide more info if needed as well.

CodePudding user response:

You can access the object property like this:

const arr = bigObj[objId];

Then you can map it into whatever you need. You would also need to be careful and check if the array actually exists:

const mappedArray = arr?.map(item => "whatever you need to map it into");

CodePudding user response:

Iterate the object keys

Object.keys(bigObj).map(key => {
   //put your logic here for keys and values e.g. key, bigObj[key]
   bigObj[key].map(obj => {
      //put your logic here for nested array object

   });
});
  • Related