我有一个像这样的对象数组:
[
{
"path": [
"attributes"
"redirectUri"
],
"message": "must be an absolute URI.",
},
{
"path": [
"attributes"
"redirectUri"
],
"message": "blabla",
},
{
"path": [
"attributes"
"anotherField"
],
"message": "second",
}
]
我想解析它并生成一个像这样的对象:
{
redirectUri: "must be an absolute URI., blabla",
anotherField: "second"
}
- 为相同的
path[1]
映射和连接message
,用逗号分隔 - 只考虑
path[1]
作为键
请帮忙,不胜感激。
我没有走得太远,我可以在ruby中做到这一点,但在javascript中不行,现在我尝试
const errorObject = result.data.appCreate.errors
.map(obj => ({ [obj.path[0]]: obj.message }))
但是我在看reduce
使用Array#reduce
遍历每个术语,这使我们可以使用结果保留一个新对象。我们还可以使用Destructuring assignment
来获得我们需要的确切属性。
let arr = [ { path: ['attributes', 'redirectUri'], message: 'must be an absolute URI.', }, { path: ['attributes', 'redirectUri'], message: 'blabla', }, { path: ['attributes', 'anotherField'], message: 'second', }, ];
let res = arr.reduce((acc, { path: [, tag], message }) => {
acc[tag] = acc[tag] ? acc[tag] + ', ' + message : message;
return acc;
}, {});
console.log(res);
实现此目的的方法之一如下:
const input = [
{
path: ["attributes", "redirectUri"],
message: "must be an absolute URI.",
},
{
path: ["attributes", "redirectUri"],
message: "blabla",
},
{
path: ["attributes", "anotherField"],
message: "second",
},
];
const output = input.reduce((prev, next) => {
const { path = [], message } = next;
const key = path[1];
prev[key] = (prev[key] || "") + message;
return prev;
}, {});
console.log(output);
# Edit1:
对于那些关心eslint no-param-reassign警告的人,我建议你们阅读以下eslint官方GitHub问题:
- https://github.com/eslint/eslint/issues/8007
- https://github.com/eslint/eslint/issues/8581
- https://github.com/eslint/eslint/issues/6339
如果你不想在这一行禁用eslint,那么修复它的一种方法是:
const output = input.reduce((prev, next) => {
const { path = [], message } = next;
const key = path[1];
return { ...prev, [key]: (prev[key] || "") + message };
}, {});
遍历对象,检查输出对象中是否存在键obj[i]['path'][1]
,如果存在则连接否则生成键值对
var obj = [
{
"path": [
"attributes",
"redirectUri"
],
"message": "must be an absolute URI.",
},
{
"path": [
"attributes",
"redirectUri"
],
"message": "blabla",
},
{
"path": [
"attributes",
"anotherField"
],
"message": "second",
}
];
var output = {};
for(let ob of obj){
if(output[ob['path'][1]] ==undefined) output[ob['path'][1]] = ob['message']
else output[ob['path'][1]] += `, ${ob['message']}`;
}
console.log(output);