skip to Main Content

I have the following javascript object and want to stringify in JSON format.
I want to skip the (key, value) pair at the specific level. In my case, I don’t want to encode user.id but want to stringify package.id.

I am using the replacer of JSON.stringify. I know the replacer function gets every key/value pair including nested objects and array items. It is applied recursively. but I need to know is there any other way around instead of creating a new object

let student = {
  id: 1, // want to skip this id.
  name: 'John',
  age: 30,
  isAdmin: false,
  courses: ['html', 'css', 'js'],
  package: {
    id: 121, // but need this id.
    name: "starter",
    price: 15
  },
  spouse: null
};

let str = JSON.stringify(student, function(key, value) {
  return key == 'id' ? undefined : value
});

console.log(str);

3

Answers


  1. this in the replacer function of JSON.stringify will hold the original object it’s called for:

    As a function, it takes two parameters: the key and the value being stringified. The object in which the key was found is provided as the replacer‘s this context.


    So you could check if any of the top-level keys exist in that object, for example, I’ve choisen age as a student has one, but the package doesn’t.

    Of course this is reversable, you could also ‘only remove the key if the object has (eg) a price key’: return !("price in this) && ...

    let student = {
      id: 1, // want to skip this id.
      name: 'John',
      age: 30,
      isAdmin: false,
      courses: ['html', 'css', 'js'],
      package: {
        id: 121, // but need this id.
        name: "starter",
        price: 15
      },
      spouse: null
    };
    
    let str = JSON.stringify(student, function(key, value) {
      return (("age" in this) && key == 'id') ? undefined : value;
    });
    
    console.log(str);
    Login or Signup to reply.
  2. You also can check for id key if it is direct key of the object or object of object.

    checking the path of the current key using the this object available within the replacer function.

    let student = {
      id: 1, // want to skip this id.
      name: 'John',
      age: 30,
      isAdmin: false,
      courses: ['html', 'css', 'js'],
      package: {
        id: 121, // but need this id.
        name: "starter",
        price: 15
      },
      spouse: null
    };
    
    let str = JSON.stringify(student, function(key, value) {
      // Track the path by appending the current key to the previous path.
      const path = (this.path || []).concat(key);
      
      // Check if the path includes 'package' and 'id'.
      if (path.includes('package') && key === 'id') {
        return value; // Include package.id
      }
      
      // Skip other 'id' properties.
      if (key === 'id') {
        return undefined;
      }
    
      // Return the value for other keys.
      return value;
    });
    
    console.log(str);
    Login or Signup to reply.
  3. Skip the ID just at the indicated level using only "id"

    const replacer = (key, value) => {
      // A stack to keep track of object depth.
      // The current depth increases with each object or array and decreases as we exit their scope.
      let stack = [];
      return (key, value) => {
        if (typeof value === 'object' && value !== null) {
          let index = stack.indexOf(value);
          if (index !== -1) {
            // Circular reference found, discard key
            return;
          }
          // Store value in our stack
          stack.push(value);
        }
        // Remove 'id' keys from nested objects, but keep the root 'id' - use === 1 to get rid of the root ID
        return (key === 'id' && stack.length > 1) ? undefined : value;
      };
    }
    
    let str = JSON.stringify(student, replacer(), 2);
    console.log(str);
    <script>
    let student = {
      id: 1,
      name: 'John',
      age: 30,
      isAdmin: false,
      courses: ['html', 'css', 'js'],
      package: {
        id: 121,
        name: "starter",
        price: 15
      },
      spouse: null
    };
    
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search