我有一个对象数组,像这样:
let obj = [
{ name: "Qwerty1", status: "Development" },
{ name: "Qwerty2", status: "Development" },
{ name: "Qwerty3", status: "Staging" },
{ name: "Qwerty4", status: "Production" },
{ name: "Qwerty5", status: "Production" }
]
我需要创建一个函数
getList(status) {
}
我将为此功能传递一个状态,例如:“开发”或“状态”或“生产”
现在,如果我将“ Production”传递给此函数,它将返回状态为“ Production”的所有对象以及状态为“ Staging”和“ Development”的所有对象的数组
如果我通过状态“ Staging”,它应返回状态为“ Staging”的所有对象和状态为“ Development”的所有对象的数组
如果我通过“ Development”,它应该只返回状态为“ Development”的对象的数组。
所以订单是生产->阶段->开发(“生产”包括“阶段”,“阶段”包括“开发”)
请注意,我无法更改此obj中的任何内容,因为它来自API。
答案 0 :(得分:0)
Filter列表,并检查对象的status
是否等于或小于status
参数。要为每个状态分配数值,请创建一个Map状态->值。
const obj = [{"name":"Qwerty1","status":"Development"},{"name":"Qwerty2","status":"Development"},{"name":"Qwerty3","status":"Staging"},{"name":"Qwerty4","status":"Production"},{"name":"Qwerty5","status":"Production"}]
const statusToValue = new Map([['Development', 0], ['Staging', 1], ['Production', 2]])
const getList = (status) => obj.filter(o => statusToValue.get(o.status) <= statusToValue.get(status))
console.log(getList('Development'))
console.log(getList('Staging'))
console.log(getList('Production'))
答案 1 :(得分:0)
找到匹配的Status
的最后一个索引,然后从0到该索引的slice
数组:
let obj = [
{ name: "Qwerty1", status: "Development" },
{ name: "Qwerty2", status: "Development" },
{ name: "Qwerty3", status: "Staging" },
{ name: "Qwerty4", status: "Production" },
{ name: "Qwerty5", status: "Production" }
]
function getList(status) {
let lastIndex;
for (let i = obj.length - 1; i >= 0; i--) {
if (obj[i].status === status) {
lastIndex = i;
break;
}
}
if (lastIndex === undefined) {
return [];
}
return obj.slice(0, lastIndex + 1);
}
console.log(getList('Development'));
console.log(getList('Staging'));
console.log(getList('Production'));
答案 2 :(得分:0)
您可以简单地使用buy()
此代码循环.filter()
,创建订单,并使用obj
检查当前项是否在层次结构中的参数.filter()
下。
status
答案 3 :(得分:0)
简单但明确:
function getList(status) {
if (status === 'C') {
return obj
}
if (status === 'B') {
return obj.filter(object => object.status === 'B' || object.status === 'A')
}
if (status === 'A') {
return obj.filter(object => object.status === 'A')
}
}
答案 4 :(得分:0)
使用对象文字将实际单词转换为数值以进行比较。这样,无论状态名称的字母顺序如何,您都可以拥有状态级别所需的顺序。
let statusLevels = {"Development": 0, "Staging": 1, "Production": 2};
let obj = [
{ name: "Qwerty1", status: "Development" },
{ name: "Qwerty2", status: "Development" },
{ name: "Qwerty3", status: "Staging" },
{ name: "Qwerty4", status: "Production" },
{ name: "Qwerty5", status: "Production" }
];
function getStatusArr(itemStatus) {
// compares the status as numerical values base on the object literal
return obj.filter(o => statusLevels[o.status] <= statusLevels[itemStatus]);
}
console.log(getStatusArr('Staging'))
//gives all levels up to and including "Staging"
//[
// {
// "name": "Qwerty1",
// "status": "Development"
// },
// {
// "name": "Qwerty2",
// "status": "Development"
// },
// {
// "name": "Qwerty3",
// "status": "Staging"
// }
//]