如何访问数组中的特定对象元素

时间:2019-02-24 13:31:09

标签: reactjs react-redux

我已经使用了map函数来使用reduce,并且得到了一组对象。 如何在“返回”中获得特定的值?

下面是控制台输出

{design job: Array(2)}
design job: Array(2)
0:
fullName: "Rakesh"
phoneno: "1111111111"
__proto__: Object
1:
fullName: "test user"
phoneno: "9176837787"
__proto__: Object
length: 2
__proto__: Array(0)
__proto__: Object

下面是我的代码

const list = appliedCandidates.reduce(
  (appliedCandidate, { Title, fullName, phoneno }) => {
    (appliedCandidate[Title] = appliedCandidate[Title] || []).push({
      fullName: fullName,
      phoneno: phoneno
    });
    return appliedCandidate;
  },
  {}
);
console.log(list);

return (
  <div>
    {Object.keys(list).map((item, i) => {
      return (
        <ul>
          {item}
          <li key={i}>{item.fullName}</li>
        </ul>
      );
    })}
  </div>
);

2 个答案:

答案 0 :(得分:0)

假设您的数据如下所示:

 const jobs = {
   "design job": [
     {
       fullName: "Rakesh",
       phoneno: "1111111111"
     },
     {
       fullName: "test user",
       phoneno: "9176837787"
     }
   ],
   "another job": [
     {
       fullName: "Rakesh",
       phoneno: "1111111111"
     },
     {
       fullName: "test user 2",
       phoneno: "9176837787"
     }
   ]
 };

以下是返回JSX以显示所有作业以及每个作业的所有应聘者的代码:

 return Object.entries(jobs).map(([title, candidates]) => (
   <ul>
     <h3>{title}</h3>
     {candidates.map((c, i) => (
       <li key={i}>{c.fullName}</li>
     ))}
   </ul>
 ));

答案 1 :(得分:0)

function iMGroot() {
  let appliedCandidates = [{
      Title: 'title-1',
      fullName: 'fullName-1',
      phoneno: 'phoneno-1'
    },
    {
      Title: 'title-11',
      fullName: 'fullName-11',
      phoneno: 'phoneno-11'
    },
    {
      Title: 'title-12',
      fullName: 'fullName-12',
      phoneno: 'phoneno-12'
    },
    {
      Title: 'title-13',
      fullName: 'fullName-13',
      phoneno: 'phoneno-13'
    }, {
      Title: 'title-14',
      fullName: 'fullName-14',
      phoneno: 'phoneno-14'
    }
  ]
  const list = appliedCandidates.reduce(
    (appliedCandidate, {
      Title,
      fullName,
      phoneno
    }) => {
      (appliedCandidate[Title] = appliedCandidate[Title] || []).push({
        fullName: fullName,
        phoneno: phoneno
      });
      return appliedCandidate;
    }, {}
  );
  console.log(list);

  return ( `<div> ${Object.keys(list).map((item, i) => {
      return (
        `<ul>
          ${list[item].map(lItem=>{
            return `
            <li>${lItem.fullName}</li>
            <li>${lItem.phoneno}</li>
            `
          })}
        </ul>`
      )
    })}</div>`
  );

}

console.log(iMGroot())

PS:请参见函数iMGroot的return语句。 由于缺少appliedCandidates的定义,因此已在上面的函数中填充了它。