gpt4 book ai didi

ecmascript-6 - 使用 map 和箭头功能将 2 个列表合二为一

转载 作者:行者123 更新时间:2023-12-03 23:08:53 24 4
gpt4 key购买 nike

我有 2 个列表,我想将它们组合起来,以便我可以将它们填充到一个列表中。我知道这可以使用嵌套的 for 循环来完成,但是,由于我必须循环的数据量,我试图避免 for 循环。我想使用箭头函数或其他任何东西来实现这一点。

列表一:

let fields = [
{
field: "Name",
fieldType: "Text"
},
{
field: "Active__c",
fieldType: "Boolean"
},
{
field: "Contact",
fieldType: "Relationship"
}
];

列表二:
let rows = [
{
contact: {
Name: "Joe",
Active__c: true,
Contact: "SomeContact"
}
},
{
contact: {
Name: "Rachel",
Active__c: true
}
},
{
contact: {
Name: "Ross",
Active__c: true
}
},
{
contact: {
Name: "Monica",
Active__c: true
}
}
];

当前代码:
let output = rows.map(row => ({
id: row.Id,
data: {
value: fields.map(field => (row.contact[field.field])),
field: fields.map(field => field.field)
}
}));

此代码的输出:
[
{
"data": {
"value": [
"Joe",
true,
"SomeContact"
],
"field": [
"Name",
"Active__c",
"Contact"
]
}
},
{
"data": {
"value": [
"Rachel",
true,
null
],
"field": [
"Name",
"Active__c",
"Contact"
]
}
},
{
"data": {
"value": [
"Ross",
true,
null
],
"field": [
"Name",
"Active__c",
"Contact"
]
}
},
{
"data": {
"value": [
"Monica",
true,
null
],
"field": [
"Name",
"Active__c",
"Contact"
]
}
}
]

所需输出:
[
data : [
[
{
field : "Name",
type: "Text",
value : "Joe"
},
{
field : "Active__c",
type: "Boolean",
value : true
},
{
field : "Contact",
type: "Relationship",
value : "SomeContact"
}
],
[
{
field : "Name",
type: "Text",
value : "Rachel"
},
{
field : "Active__c",
type: "Boolean",
value : false
},
{
field : "Contact",
type: "Relationship",
value : "SomeContact Two"
}
],
[
...
],
[
...
]
]
]

我怎样才能做到这一点?

最佳答案

data属性是唯一的,必须在创建对象时内联定义(而不是您在所需输出中拥有的数组)。你要 map fields数组到 rows 的每个元素然后填写每个field数据与 row数据(如果存在)。另外,我看不到 Id内的任何行对象上的字段 rows大批。此代码集 null如果 field不存在:

let output = {
data: rows.map(({ contact }) =>
fields.map(({ field, fieldType: type }) => ({
field,
type,
value: field in contact ? contact[field] : null // Set null if contact has no field
}))
)
}

运行此代码片段以查看结果:

let fields = [
{
field: "Name",
fieldType: "Text"
},
{
field: "Active__c",
fieldType: "Boolean"
},
{
field: "Contact",
fieldType: "Relationship"
}
];

let rows = [
{
contact: {
Name: "Joe",
Active__c: true,
Contact: "SomeContact"
}
},
{
contact: {
Name: "Rachel",
Active__c: true
}
},
{
contact: {
Name: "Ross",
Active__c: true
}
},
{
contact: {
Name: "Monica",
Active__c: true
}
}
];

let output = {
data: rows.map(({ contact }) =>
fields.map(({ field, fieldType: type }) => ({
field,
type,
value: field in contact ? contact[field] : null
}))
)
}

document.getElementById('output').appendChild(
document.createTextNode(JSON.stringify(output, null, 2))
);
<pre id="output"></pre>

关于ecmascript-6 - 使用 map 和箭头功能将 2 个列表合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60222532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com