简体   繁体   English

在 react 和 javascript 中,如何正确映射此对象的键值?

[英]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.我有一个对象,其中每个键都是唯一的 id,键值是一个对象数组。

I have a prop, lets call it 'objId' whos value is one of the unique ids on the object我有一个道具,我们称之为“objId”,它的值是该对象的唯一 ID 之一

I want to map the array on the object where its key matches the prop 'objId'我想将数组映射到其键与道具“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.我想将 bigObj.a123 映射到我的组件中,因为它与 objId 道具匹配。

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

   });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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