首页 > 解决方案 > 如何将以下内容映射为预期结果的反应状态

问题描述

Json数据如下

const data= 
{
   "id":1,
   "title":"Test title",
   "results":[
      {
         "rowId":1,
         "records":[
            {
               "attribute":"Id",
               "value":"id1"
            },
            {
               "attribute":"title",
               "value":"Perform data"
            }
         ]
      },
      {
         "rowId":2,
         "records":[
            {
               "attribute":"Id",
               "value":"id2"
            },
            {
               "attribute":"title",
               "value":"Test data"
            }
         ]
      }
   ]
}

预期的:

0:Id: "id1",
  title:"Perform data"
1:Id: "id2",
  title:"Test data"

标签: reactjs

解决方案


将数据结果映射到访问记录数组的新对象,以简化为具有正确映射键的对象。

data.results.map(({ records }) =>
  records.reduce(
    (obj, { attribute, value }) => ({
      ...obj,
      [attribute]: value
    }),
    {}
  )
);

const data = {
  id: 1,
  title: "Test title",
  results: [
    {
      rowId: 1,
      records: [
        {
          attribute: "Id",
          value: "id1"
        },
        {
          attribute: "title",
          value: "Perform data"
        }
      ]
    },
    {
      rowId: 2,
      records: [
        {
          attribute: "Id",
          value: "id2"
        },
        {
          attribute: "title",
          value: "Test data"
        }
      ]
    }
  ]
};

const result = data.results.map(({ records }) =>
  records.reduce(
    (obj, { attribute, value }) => ({
      ...obj,
      [attribute]: value
    }),
    {}
  )
);

console.log(result);


推荐阅读