我有以下JSON
[
{
"Id":1068,
"Name":"jone",
"SortOrder":0
},
{
"Id":1077,
"Name":"John ",
"SortOrder":0
},
{
"Id":1074,
"Name":"sasasa",
"SortOrder":0
},
{
"Id":1078,
"Name":"fdfdfd",
"SortOrder":0
},
{
"Id":1029,
"Name":"fdfdfd",
"SortOrder":0
},
{
"Id":1076,
"Name":"sdf",
"SortOrder":0
},
{
"Id":1030,
"Name":"erer",
"SortOrder":0
},
{
"Id":11,
"Name":"tryryr",
"SortOrder":0
},
{
"Id":1008,
"Name":"bvbf",
"SortOrder":0
},
{
"Id":9,
"Name":"jkk",
"SortOrder":0
},
{
"Id":19,
"Name":"pioku",
"SortOrder":0
},
{
"Id":5,
"Name":"cssxs",
"SortOrder":0
},
{
"Id":1009,
"Name":"mhmh",
"SortOrder":0
}
]
现在,我需要通过传递ID从JSON中删除商品。例如,当我向函数传递1068,1077
id(逗号分隔)时,我需要从JSON中删除相关数据。
[ { "Id":1074, "Name":"sasasa", "SortOrder":0 }, { "Id":1078, "Name":"fdfdfd", "SortOrder":0 }, { "Id":1029, "Name":"fdfdfd", "SortOrder":0 }, { "Id":1076, "Name":"sdf", "SortOrder":0 }, { "Id":1030, "Name":"erer", "SortOrder":0 }, { "Id":11, "Name":"tryryr", "SortOrder":0 }, { "Id":1008, "Name":"bvbf", "SortOrder":0 }, { "Id":9, "Name":"jkk", "SortOrder":0 }, { "Id":19, "Name":"pioku", "SortOrder":0 }, { "Id":5, "Name":"cssxs", "SortOrder":0 }, { "Id":1009, "Name":"mhmh", "SortOrder":0 } ]
当将1009,1068,1074,1078,1029,1076,1030,11,1008
传递到JSON后面的函数时,将得到结果。
[
{
"Id":9,
"Name":"jkk",
"SortOrder":0
},
{
"Id":19,
"Name":"pioku",
"SortOrder":0
},
{
"Id":5,
"Name":"cssxs",
"SortOrder":0
},
{
"Id":1009,
"Name":"mhmh",
"SortOrder":0
}
]
什么是最有效的方法?并请注意。我不能使用ES6或ES5,因为某些ES5,ES6功能无法在IE和Safari浏览器中使用。
答案 0 :(得分:4)
这可以解决问题。可以使用诸如.map
或.filter
之类的Array方法使它变得不那么冗长。
var myFilter = [1009,1068,1074,1078,1029,1076,1030,11,1008];
var myData = [
{ "Id":1074, "Name":"sasasa", "SortOrder":0 },
{ "Id":9, "Name":"jkk", "SortOrder":0 },
{ "Id":19, "Name":"pioku", "SortOrder":0 },
{ "Id":5, "Name":"cssxs", "SortOrder":0 },
{ "Id":1009, "Name":"mhmh", "SortOrder":0 }
];
function filterOut(data, filter){
result = [];
for (let i = 0; i < data.length; i++){
if(filter.indexOf(parseInt(data[i].Id)) == -1){
result.push(data[i]);
}
}
return(result);
}
var output = filterOut(myData, myFilter);
console.log(output);
(请注意,您期望的结果不正确,因为其中包含1009
,这是您要求过滤掉的ID值之一。为简便起见,我从列表中删除了一些数据对象。)
编辑: 我刚刚注意到您的“没有现代JS”要求。我想我已经从ES5开始删除了所有内容。
答案 1 :(得分:2)
我的建议是编写最简单的可行代码,然后进行polyfill或transpile以支持您的目标环境。
请记住,这是一个用现代风格编写的简单版本:
const removeByIds = (ids, idNbrs = ids.split(',').map(Number)) =>
(data) => data.filter(({Id}) => !idNbrs.includes(Id))
const data = [{"Id": 1077, "Name": "John ", "SortOrder": 0}, {"Id": 9, "Name": "jkk", "SortOrder": 0}, {"Id": 19, "Name": "pioku", "SortOrder": 0}, {"Id": 5, "Name": "cssxs", "SortOrder": 0}]
console .log (
removeByIds ('1009,1068,1074,1078,1029,1076,1030,11,1008') (data)
)