我有一个如下所示的数组
[
{
"id": 42,
"name": "updateDate",
"displayName": "UPDATE DATE",
"uiControl": "DATERANGE",
"dataType": "STRING",
"uiOrder": 1,
},
{
"id": 44,
"name": "name",
"displayName": "First Name",
"uiControl": "TEXTBOX",
"dataType": "STRING",
"uiOrder": 1,
},
]
我想使用属性UiControl === DATERANGE
过滤此数组中的对象,并从过滤后的对象中创建2个对象,并将'FROM'
和'TO'
附加到name和displayname属性中,如图所示下面
最终输出:
[{
"id": 42,
"name": "fromupdateDate", // 'from'appended to name property
"displayName": "FROM UPDATE DATE", // 'FROM' appended to displayName property
"uiControl": "DATERANGE",
"dataType": "STRING",
"uiOrder": 1,
},
{
"id": 42,
"name": "toupdateDate", // 'to' appended to name property
"displayName": "TO UPDATE DATE", // 'TO' appended to displayName
"uiControl": "DATERANGE",
"dataType": "STRING",
"uiOrder": 1,
},
{ // this object stays the same
"id": 44,
"name": "name",
"displayName": "First Name",
"uiControl": "TEXTBOX",
"dataType": "STRING",
"uiOrder": 1,
}]
We can create such an array in multiple ways, but I want to find an optimized way of creating such an object.
答案 0 :(得分:0)
flatMap
将执行您想要的操作:
const input = [{
"id": 42,
"name": "updateDate",
"displayName": "UPDATE DATE",
"uiControl": "DATERANGE",
"dataType": "STRING",
"uiOrder": 1,
},
{
"id": 44,
"name": "name",
"displayName": "First Name",
"uiControl": "TEXTBOX",
"dataType": "STRING",
"uiOrder": 1,
},
];
const output = input.flatMap(v => v.uiControl === "DATERANGE"
? [
{ ...v,
name: `from${v.name}`,
displayName: `FROM ${v.displayName}`
},
{ ...v,
name: `to${v.name}`,
displayName: `TO ${v.displayName}`
}
]
: [v]);
console.log(output);
请注意,您必须在esnext
支持下进行编译。有关更多详细信息,请参见this question。它也不会在IE或Edge上开箱即用。如果这是用例中的问题,则需要使用polyfill或像这样依靠map
+ reduce
:
const output = input.map(v => v.uiControl === "DATERANGE"
? [
{ ...v,
name: `from${v.name}`,
displayName: `FROM ${v.displayName}`
},
{ ...v,
name: `to${v.name}`,
displayName: `TO ${v.displayName}`
}
]
: [v])
.reduce((acc, cur) => (acc.push(...cur), acc), []);