0

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 } } 
11
  • Yes, there is a way, but you'll have to assign that 0 to each individual property. So a solution will have loops, and for the nesting you will probably want to use recursion. Commented Mar 19, 2021 at 22:55
  • 1
    "Don't ask about... Questions you haven't tried to find an answer for (show your work!)" tour Commented Mar 19, 2021 at 22:55
  • "Don't ask about... Questions you haven't tried to find an answer for (show your work!)" - my try for it at this stage is to just type all those properties and make them 0. if it was python, i guess i'd be able to make a loop for it, but as i mentioned, my js is still crap, so the answer to my question was meant to be a building block for my loop understaning in js Commented Mar 19, 2021 at 23:03
  • Object.keys will give an array of keys for an object, then you can loop over those keys. Mdn is an excellent resource for javascript api questions. You can use for (const key of arr) { to create a for loop, or use arr.forEach() to loop over using a callback. Commented Mar 19, 2021 at 23:03
  • Can you an example object and what it would look like converted? Commented Mar 19, 2021 at 23:16

2 Answers 2

1

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}));

Sign up to request clarification or add additional context in comments.

1 Comment

This solution is most understandable for me. It's closest to what i'm used to in python. That is exactly what i needed.
0

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.