如何仅将所需字段保留在JavaScript对象中?

时间:2018-07-24 16:24:59

标签: javascript

例如,我有

const eva = {name: "Eva", age: 3, hobby: "dance", state: "NY"};
const ann = {name: "Ann", age: 9, hobby: "read", state: "WA", schoolyear: 3};

我想要一个修整功能,该功能只保留我想要的字段。

const fields = ["name", "age", "state"]

输出将是

const eva2 = {name: "Eva", age: 3, state: "NY"};
const ann2 = {name: "Ann", age: 9, state: "WA"};

我无法遍历所有字段并删除循环内的字段。这样可以更早地结束循环。

谢谢!

3 个答案:

答案 0 :(得分:1)

使用Delete从对象中删除键。创建一个函数,该函数将接受从中删除键的对象。现在在该函数中执行Object.keys,这将创建一个包含对象所有键的数组。然后迭代该数组,并使用indexOf检查主数组中是否存在此项。如果不是,则使用delete运算符从对象中删除密钥

const eva = {
  name: "Eva",
  age: 3,
  hobby: "dance",
  state: "NY"
};
const ann = {
  name: "Ann",
  age: 9,
  hobby: "read",
  state: "WA",
  schoolyear: 3
};


const fields = ["name", "age", "state"];

function delKey(obj) {
  let objKeys = Object.keys(obj)
  objKeys.forEach(function(item) {
    if (fields.indexOf(item) === -1) {
      delete obj[item]
    }
  })
  return obj
}
console.log(delKey(eva))
console.log(delKey(ann))

答案 1 :(得分:0)

使用删除功能,这是一个简单的示例:

const eva = {name: "Eva", age: 3, hobby: "dance", state: "NY"};
const ann = {name: "Ann", age: 9, hobby: "read", state: "WA", schoolyear: 3};
const fields = ["name", "age", "state"]
// get the keys in the object
var keys = Object.keys(eva);
// loop over all the keys
for(var i = 0; i < keys.length; i++)
  // check if it's in the array of fields to keep 
  if (fields.indexOf(keys[i]) < 0)
     // delete the property because it isnt in fields
     delete eva[keys[i]];

console.log(eva);

答案 2 :(得分:0)

您可以使用Array.prototype.reduce()

更加简洁
const eva = { name: "Eva", age: 3, hobby: "dance", state: "NY" };
const allowedKeys = ['name', 'age', 'state'];

const newObject = Object.keys(eva).reduce(function(newObj, key) {
    if (allowedKeys.indexOf(key) !== -1) {
        newObj[key] = eva[key];
    }
    return newObj;
}, {});

console.log(newObject);