简体   繁体   中英

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

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.

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");

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

   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM