-2

For example, I have

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

I want to have a trim function, which only keeps the fields I want.

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

and the output will be

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

I can't iterate through all fields and delete fields inside the loop. That will end the loop earlier.

Thanks!

Danield
  • 121,619
  • 37
  • 226
  • 255
Yixing Liu
  • 2,179
  • 1
  • 20
  • 36

4 Answers4

1

Use delete to delete an key from an object. Create a function which will accept an object from where the keys will be delete. Now inside that function do Object.keys which will create an array of all the keys of the object.Then iterate this array and use indexOf to check if this item is present in the main array. If not then use delete operator to delete the key from the object

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))
brk
  • 48,835
  • 10
  • 56
  • 78
0

Use the delete function, here is a quick example:

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);
Adam H
  • 1,750
  • 1
  • 9
  • 24
0

You can do it more concisely using 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);
unclexo
  • 3,691
  • 2
  • 18
  • 26
0

also you if you want default values to shape your object.

function getShapedValue(shape, defaultValue) {
    const shaped = {};

    for(const key of Object.keys(shape)) {
        if(defaultValue.hasOwnProperty(key))
            shaped[key] = defaultValue[key]
        else
            shaped[key] = shape[key]
    }

    return shaped;
}


const shape = { name: "", age: null }

const userNameAge = getShapedValue(shape, fullUserObject)

LeulAria
  • 333
  • 3
  • 9