我有这样的javascript数组
let attributeSet = [
{
"name" : "Capacity",
"value" : "1 TB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND",
}
]格式应该是id-value对。此外,id的顺序应该是递增的。像这样
output = 3-1 TB | 4-5 inch | 5-3D Nand有人能帮忙吗?
发布于 2021-01-04 07:28:16
在ES6中,您可以尝试如下:
let output = attributeSet.sort((a, b) => a.id - b.id).map(i => `${i.id}-${i.value}`).join(' | ');发布于 2021-01-04 07:26:50
使用id使用Array.sort()对数组进行排序,并使用Array.join()将它们连接起来
const attributeSet = [
{
"name" : "Capacity",
"value" : "1 TB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND",
}
]
attributeSet.sort((a, b) => a.id - b.id);
const output = attributeSet.map(item => item.id + '-' + item.value).join(" | ")
console.log(output);
发布于 2021-01-04 07:28:24
您可以首先根据id对数组进行排序,然后从该排序数组中迭代和创建新数组,
attributeSet = [
{
"name" : "Capacity",
"value" : "1 TB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND",
}
]
attributeSet.sort((a,b) => parseInt(a.id) - parseInt(b.id));
let res = attributeSet.map(item => {
return item.id+'-'+item.value;
})
console.log(res.join(' | '));
https://stackoverflow.com/questions/65559026
复制相似问题