gpt4 book ai didi

javascript - 将动态 HTML 字段数组中的值减少到最紧凑的形式

转载 作者:行者123 更新时间:2023-11-30 11:05:25 25 4
gpt4 key购买 nike

我有一个带有动态 recipients 字段数组的 HTML 表单,其中每个数组项都有 nameemail 字段。字段名称是使用 [array_name].[item_index].[field_name] 模式唯一生成的。当我提交表单时,它会生成以下 JSON:

[{
name: 'recipients.0.name',
value: 'John'
}, {
name: recipients.0.email',
value: 'john@test.com'
},{
name: 'recipients.1.name',
value: 'Sam'
}, {
name: recipients.1.email',
value: 'sam@test.com'
}]

我需要将其转换为最紧凑的形式,如下所示:

{
recipients: [{
name: 'John',
email: 'john@test.com'
}, {
name: 'Sam',
email: 'sam@test.com'
}]
}

执行此操作最优雅的方法是什么?欢迎使用 Lodash 的示例。

编辑:字段名称仅供引用。解决方案应该适用于模式 [array_name].[item_index].[field_name] 之后的任何名称,而不仅仅是 recipients.[item_index].[field_name]

这是我的实现,我对它不是很满意:

const fields = [{
name: 'recipients.0.name',
value: 'John',
},
{
name: 'recipients.0.email',
value: 'john@test.com',
},
{
name: 'recipients.1.name',
value: 'Sam',
},
{
name: 'recipients.1.email',
value: 'sam@test.com',
},
];

const compactFieldArrays = fields.reduce((result, field) => {
const [fieldArrayName, fieldArrayItemIndex, fieldName] = field.name.split('.');
let fieldArray = result[fieldArrayName];

if (!fieldArray) {
fieldArray = [];
result[fieldArrayName] = fieldArray;
}

let fieldArrayItem = fieldArray[fieldArrayItemIndex];
if (fieldArrayItem) {
fieldArrayItem[fieldName] = field.value;
} else {
fieldArrayItem = {
[fieldName]: field.value,
};
fieldArray.push(fieldArrayItem);
}
return result;
}, {});

console.log(compactFieldArrays);

最佳答案

仅使用 JS:

const data = [{"name":"recipients.0.name","value":"John"},{"name":"recipients.0.email","value":"john@test.com"},{"name":"recipients.1.name","value":"Sam"},{"name":"recipients.1.email","value":"sam@test.com"}]

// `reduce` over the array
const out = data.reduce((acc, { name, value }) => {

// `split` the name on the period, and pop off the key
// and the recipient id
const arr = name.split('.');
const key = arr.pop();
const recipient = arr.pop();

// Create either a new object or update the existing
// object on the accumulator
acc[recipient] = { ...acc[recipient] || {}, [key]: value };
return acc;
}, {});

console.log(Object.values(out));

关于javascript - 将动态 HTML 字段数组中的值减少到最紧凑的形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55848764/

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