我有一个对象数组
使用for循环我根据属性phoneType的值重新排序我的对象数组。由于这是来自api的数据响应,我所说的总是将我的电话号码首先放在我的回归档案中。
问你...我不确定这是否是最好的方法。有没有不同的方法来实现这一目标?我正在考虑使用Object.Keys来做这件事,但无法弄明白。
这是我的循环:
export function examplefunctionForStackOverflow(phoneNumbers) {
const phoneNumberArray = [];
if (typeof phoneNumbers !== 'undefined') {
for (const i in phoneNumbers) {
const number = phoneNumbers[i].number;
const phoneType = phoneNumbers[i].phoneType;
phoneNumbers[i].phoneType === "Primary" ?
phoneNumberArray.unshift({
key: phoneType,
value: number
}) :
phoneNumberArray.push({
key: phoneType,
value: number
});
}
}
return phoneNumberArray;
}
data: {
phoneNumbers: [{
number: "(999) 999-9999",
extension: "",
phoneType: "CELL"
},
{
number: "(888) 888-8888",
extension: "",
phoneType: "Primary"
},
{
number: "(777) 777-7777",
extension: "777",
phoneType: "WORK"
}
]
答案 0 :(得分:2)
您可以简单地对数组进行排序:
let data = {
phoneNumbers: [{
number: "(999) 999-9999",
extension: "",
phoneType: "CELL"
},
{
number: "(888) 888-8888",
extension: "",
phoneType: "Primary"
},
{
number: "(777) 777-7777",
extension: "777",
phoneType: "WORK"
}
]
};
data.phoneNumbers.sort((a, b) => {
if (a.phoneType === 'Primary') return -1;
return 1;
});
console.log(data.phoneNumbers);