我有一个应用程序,我希望能够根据对象中的 orderId 值呈现内容堆栈。
{
"hero": {
"body": "test body",
"orderId": 1
},
"journey": {
"body": "test body",
"orderId": 0
},
"banner": {
"body": "test body",
"orderId": 2
}
}
我已经尝试过类似这样的方法来创建数组
Object.entries(content).sort(function(a, b) {
return a[1].orderId - b[1].orderId;
});
答案 0 :(得分:3)
您唯一缺少的部分是获取键,您可以通过在已排序数组上使用 map 并从该数组中检索第一个元素来获取它。
sortedData.map((a) => a[0])
const content = {
hero: {
body: "test body",
orderId: 1,
},
journey: {
body: "test body",
orderId: 0,
},
banner: {
body: "test body",
orderId: 2,
},
};
const result = Object.entries(content)
.sort((a, b) => a[1].orderId - b[1].orderId)
.map((a) => a[0]);
console.log(result);
答案 1 :(得分:0)
let json = {
"hero": {
"body": "test body",
"orderId": 1
},
"journey": {
"body": "test body",
"orderId": 0
},
"banner": {
"body": "test body",
"orderId": 2
}
}
let arr = [];
Object.entries(json).forEach(ele => {
let keyword = ele[0];
id = ele[1].orderId;
arr[id] = keyword;
})
console.log(arr)