reactjs - 如何将以下内容映射为预期结果的反应状态
问题描述
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"
解决方案
将数据结果映射到访问记录数组的新对象,以简化为具有正确映射键的对象。
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);
推荐阅读
- veins - 如何为“相扑”和“静脉”添加新属性?
- c - 尽管没有完全填充,我如何编写一个由 20 个结构组成的结构数组?
- javascript - 我应该如何在 React.js 类组件中返回 HTML 而不会出错?
- flutter - TabBar 必须在 TabBarView Flutter 之前运行 OnTap
- ruby-on-rails - Rails 6 + Postcss + webpack:TypeError:this.getOptions 不是函数
- javascript - 有没有更好的方法来断言所有拦截的请求在赛普拉斯中都是成功的?
- java - 使用流从Java中的csv文件中按日期和时间排序
- php - 当有人订阅时,自动从商家支付 PayPal 佣金
- mysql - 查询以列出某些值不可用的列
- google-cloud-firestore - Firestore 历史使用文档读取、写入、删除