来自API的我的Json结果如下
Json结果:
"Issues": [{
"Id": null,
"Key": null,
"Values": [{
"Key": "Display Name",
"Value": "Rya"
},
{
"Key": "UserName",
"Value": "RH"
},
{
"Key": "Count",
"Value": "350"
}
]
},
{
"Id": null,
"Key": null,
"Values": [{
"Key": "Display Name",
"Value": "Mike"
},
{
"Key": "UserName",
"Value": "ML"
},
{
"Key": "Count",
"Value": "90"
}
]
}
]
我按照以下方式进行了映射 -
.Issues.map(o =>
o.Values.reduce((acc, {
Key,
Value
}) =>
(acc[Key] = Value, acc), {}));
映射的结果如下 -
{ "Display Name": 'Rya', "UserName" : "RH", value: 350 },
{ "Display Name": 'Mike', "UserName" : "ML", value: 90 }
期望的结果:
{ "Display Name": 'Rya', "UserName" : "RH" },
{ "Display Name": 'Mike', "UserName" : "ML"}
根据我的要求,我想忽略所需结果中显示的最后一个元素。
答案 0 :(得分:1)
一种解决方案是在reduce之前添加一个过滤器,以过滤掉具有不需要的Count
属性的对象。
.Issues.map(o =>
o.Values
.filter(({ Key }) => Key !== 'Count')
.reduce((acc, {
Key,
Value
}) =>
(acc[Key] = Value, acc), {}));
您还可以在缩小期间通过在Key === 'Count'
时不添加对象来内联过滤。
注意:JS对象中没有最后一个属性。它是一组属性,其实际顺序依赖于实现且不可靠。例如,在不同的浏览器和平台上打印对象可以给出任何顺序,没有什么能保证一致性。
答案 1 :(得分:1)
最简单的解决方案是map,slice和reduce的组合:
json.Issues.map(b =>
b.Values.slice(0, -1).reduce((c,d) => {
c[d.Key] = d.Value;
return c;
}, {}));
演示:
let j = {
"Issues": [{
"Id": null,
"Key": null,
"Values": [{
"Key": "Display Name",
"Value": "Rya"
},
{
"Key": "UserName",
"Value": "RH"
},
{
"Key": "Count",
"Value": "350"
}
]
},
{
"Id": null,
"Key": null,
"Values": [{
"Key": "Display Name",
"Value": "Mike"
},
{
"Key": "UserName",
"Value": "ML"
},
{
"Key": "Count",
"Value": "90"
}
]
}
]
};
let r = j.Issues.map(b =>
b.Values.slice(0, -1).reduce((c, d) => {
c[d.Key] = d.Value;
return c;
}, {}));
console.log(r);
答案 2 :(得分:0)
.Issues.map(o => o.Values.reduce((acc, {Key, Value}) => (Key !== 'Count') ? (acc[Key] = Value, acc) : acc, {}));

完整代码:
const j = {"Issues": [
{
"Id": null,
"Key": null,
"Values": [
{
"Key": "Display Name",
"Value": "Rya"
},
{
"Key": "UserName",
"Value": "RH"
},
{
"Key": "Count",
"Value": "350"
}
]
},
{
"Id": null,
"Key": null,
"Values": [
{
"Key": "Display Name",
"Value": "Mike"
},
{
"Key": "UserName",
"Value": "ML"
},
{
"Key": "Count",
"Value": "90"
}
]
}
]
}
const r = j.Issues.map(o => o.Values.reduce((acc, {Key, Value}) => (Key !== 'Count') ? (acc[Key] = Value, acc) : acc, {}));
console.log(JSON.stringify(r, null, 2))

答案 3 :(得分:0)
请注意,在reduce方法中,该函数也在当前索引中传递,并且正在调用数组reduce。因此,如果您想忽略数组的最后一个元素,您可以执行以下操作:
Issues.map(o =>
o.Values.reduce((acc, {Key, Value}, idx, arry) => {
if(idx < arry.length -1)
acc[Key] = Value;
return acc;
}, {}
);
答案 4 :(得分:0)
要删除最后一个元素而不管数组中有多少项,我会赞成这样的事情:
let result = data.Issues.map(issue => {
let temp = issue.Values;
temp.splice(-1);
return temp.reduce((acc, {Key, Value}) => (acc[Key] = Value, acc), {});
});
这是a fiddle