gpt4 book ai didi

javascript - 数组转换嵌套对象

转载 作者:行者123 更新时间:2023-12-03 05:22:52 36 4
gpt4 key购买 nike

我想转换以下数组:

 let errors = [
{
field: "data.time",
message: "less length than allowed"
},
{
field: "data.time",
message: "wrong format"
},
{
field: "data.age",
message: "too young"
},
{
field: "data.age",
message: "not enough information"
}
];

进入:

[
{ time: "less_length_than_allowed <br> wrong_format"},
{ age: "too_young <br> not_enough_information"},
]

我基本上想删除字符串“data”。对于每个字段属性。然后合并数组,以公共(public)字段为对象键,消息串联为值。

这是我到目前为止所拥有的:

var removedData = errors.map(item => {
item.field = item.field.slice(5);
return item
});

var computedErrors = _.chain(removedData).groupBy('field').value();

最佳答案

您可以在纯js中使用reduce()返回以下结果。

let errors = [{
field: "data.time",
message: "less length than allowed"
}, {
field: "data.time",
message: "wrong format"
}, {
field: "data.age",
message: "too young"
}, {
field: "data.age",
message: "not enough information"
}];

var o = {}
var result = errors.reduce(function(r, e) {
var key = e.field.split('.')[1];
var message = e.message.replace(/\s/g, '_');

if (!o[key]) {
o[key] = {[key]: message}
r.push(o[key])
} else {
o[key][key] += ' <br> ' + message
}
return r;
}, [])

console.log(result)

关于javascript - 数组转换嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41300889/

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