简体   繁体   中英

Change all properties of an object

Is there a way to change all properties of an object to a given value, for example to 0? Will it work with nested objects?

I guess it's a noob question, but i started messing around with js only few days ago.

EDIT:

basically it looks like this:

var obj1 = {
  obj11: {
    a11: 1
    b11: 2
    c11: 321
  },

  obj12: {
    a12: 31
    b12: 65
    c12: 8776
  }
}

All those values are affected by some other functions. I wanted to make a "reset" function that would set all those values to 0. My expected output is:

{
  obj11: {
    a11: 0
    b11: 0
    c11: 0
  },

  obj12: {
    a12: 0
    b12: 0
    c12: 0
  }
}

 let obj1 = { obj11: { a11:1, b11:2, c11:321, }, obj12: { a12:31, b12:65, c12:8776, }, }; // Declare a function with a single argument o. function reset(o) { // Loop through all of the properties of the argument object o for([key, value] of Object.entries(o)) { const t = typeof value; switch(t) { // If the current property has an object value, handle that recursively. case 'object': reset(value); break; // If the current property has a numeric value, set the value to 0. case 'number': o[key] = 0; break; // Otherwise print some status information. default: console.log('The property '+key+'is of an unhandled type ('+t+').'); } } } reset(obj1); // Print the result for convenience. console.log(JSON.stringify({obj1}));

One way to do this is to take advantage of JSON.stringify() . Using its replacer argument, you can specify how each value should be transformed. This method will also recursively traverse your object, allowing you to change all values. As this function converts your object to a string, you'll need to convert it back using JSON.parse() :

 const obj1 = { obj11: { a11: 1, b11: 2, c11: 321 }, obj12: { a12: 31, b12: 65, c12: 8776 } }; const res = JSON.parse(JSON.stringify(obj1, (key, value) => Object(value) === value? value: 0)); console.log(res);

The above uses an arrow function , which gets passed in a key and a value. This will be called for every key/value in your object. The value that you return from the arrow function is the new resulting value in the new object. In this case, that value is the is 0 when the value isn't an object, otherwise, if it is an object, we just return the original object.

Note : If you have an object type that isn't serializable (such as a function) as one of your values, then this method will remove that key-value pair.


If your object has a consistent structure and doesn't contain infinitely nested objects, you might find it more straightforward to loop over the keys of your obj1 ( obj11 and obj12 ) using a for..in loop, and then the keys of the inner objects which you can obtain by using the currently looped on key from your outer loop:

 const obj1 = { obj11: { a11: 1, b11: 2, c11: 321 }, obj12: { a12: 31, b12: 65, c12: 8776 } }; const res = {}; for(const key in obj1) { res[key] = {}; for(const innerKey in obj1[key]) { res[key][innerKey] = 0; } } console.log(res);


Finally, you could use a recursive approach, where you use a function to loop the entries (a [[key, value], ...] pair array) of your object, with .map() to convert every value to a 0 . You can then use Object.fromEntries() to build your object back together from the entries array. If you encounter an object as one of your values, you can recall this function to apply the same logic to the nested value:

 const obj1 = { obj11: { a11: 1, b11: 2, c11: 321 }, obj12: { a12: 31, b12: 65, c12: 8776 } }; const changeVals = (obj, newVal) => Object.fromEntries(Object.entries(obj).map( ([key, val]) =>.Array?isArray(val) && Object(val) === val && typeof val === "object", [key, changeVals(val: newVal)], [key; newVal] ) ). console,log(changeVals(obj1; 0));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM