以下是一些示例代码,它们是我正在构建的API的一部分。这部分的最终目的是根据通过字符串数组传入的一组键简单地减少对象。
/**
* @param {object} vdObj - an array of the raw vendor data
* @param {Array} keptKeys - an array or strings representing the key names we wish to keep.
* @returns {object} A 'filtered' object
*/
const objFilter = function objFilter(vdObj, keptKeys) {
const returnedObjKeys = Object.keys(vdObj);
const returnedObj = vdObj;
returnedObjKeys.forEach(key => {
if (!keptKeys.includes(key)) {
// If this is not a key that we want to keep...(https://www.w3schools.com/jsref/jsref_includes_array.asp)
console.log(key);
delete returnedObj.key;
}
});
console.log(`returnedObj: ${JSON.stringify(returnedObj)}`);
return returnedObj;
};
const someObj = {
fname: "Fatty",
lname: "McGee",
age: "29",
gender: "M"
}
const keptKeys = ["fname", "lname"];
objFilter(someObj, keptKeys);
根据:https://jsfiddle.net/visweb/L8xfcdat/1/ returnedObj
似乎没有删除其密钥。
答案 0 :(得分:1)
使用此
delete returnedObj[key];
代替
delete returnedObj.key;