3

I want to remove all test keys from an array of objects. So each object that contains test should be processed by the function, to remove that key.

const obj = [{
  address: "asda",
  city: "asdasd",
  country: "1",
  description: {
    test: 123,
    name: 'name'
  },
  id: {
    test: 152,
    idB: 'n'
  },
  code: "asdas     ",
  test: 156,
}]

const arr = () => {
  const newKeys = obj.flatMap(item => Object.entries(item))
  const condition = newKeys.filter(i => i[0] !== 'test')
  return Object.fromEntries(condition)
}

console.log(arr())

Now i did to remove only the test from main object but i can't figure out how to remove each test from the rest objects inside main object. How to do this in my code?

1
  • 1
    To understand recursion one must first understand recursion. Commented Jun 1, 2021 at 9:30

4 Answers 4

4

Another option could be to use JSON.stringify() with a replacer function to filter your keys. The replacer is called for each key-value pair as JSON.stringify recursively walks through your array/objects, allowing you to remove key-value pairs by returning undefined:

const obj = [{ address: "asda", city: "asdasd", country: "1", description: { test: 123, name: 'name' }, id: { test: 152, idB: 'n' }, code: "asdas     ", test: 156, }];

const removeKey = (obj, keyToRemove) => JSON.parse(JSON.stringify(obj,
  (key, val) => key === keyToRemove ? undefined : val)
);

console.log(removeKey(obj, "test"));

Please note: This solution assumes your object is stringifiable (for example, doesn't consist of functions), and your keys do not have values of undefined (as undefined values are removed from the result).

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

1 Comment

1

try this

const obj = [{
  address: "asda",
  city: "asdasd",
  country: "1",
  description: {
    test: 123,
    name: 'name'
  },
  id: {
    test: 152,
    idB: 'n'
  },
  code: "asdas     ",
  test: 156,
}]




function removeTestKey(obj) {
  //check if there are any test property and removes it
  obj.test != undefined ? delete obj.test : null;

  // loop throw the object keys and thier sub objects
  for (let subObj in obj) {
    if (typeof obj[subObj] == "object") {
      removeTestKey(obj[subObj]);
    }
  }
}

obj.forEach(obj => {
  removeTestKey(obj)
})


console.log(obj)

Comments

0

You could create a recursive function that removes the desired key recursively. This recursive function could take in the object and the key to remove as parameters.

Using Object.keys(...) method, get an array of the keys of the object passed in as an argument and then using the reduce() method, remove the desired key recursively.

const obj = [
  {
    address: 'asda',
    city: 'asdasd',
    country: '1',
    description: {
      test: 123,
      name: 'name',
    },
    id: {
      test: 152,
      idB: 'n',
    },
    code: 'asdas',
    test: 156,
  },
];

function removeKey(obj, keyToRemove) {
  return Object.keys(obj).reduce((acc, key) => {
    // if the value of the current key is another object,
    // make a recursive call to remove the
    // key from the nested object
    if (typeof obj[key] === "object") {
      acc[key] = removeKey(obj[key], keyToRemove);
    }
    // if the current key is not the key that is to be removed,
    // add the current key and its value in the accumulator
    // object
    else if (key !== keyToRemove) {
      acc[key] = obj[key];
    }
    return acc;
  }, {});
}

const removeKeys = (arr, keyToRemovej) => {
  return arr.map(obj => removeKey(obj, keyToRemovej));
};

console.log(removeKeys(obj, "test"));

Comments

0

You could take a recursive approach and destructure unwanted key and keep the rest.

const
    getValue = (v, fn) => {
        if (Array.isArray(v)) return v.map(fn);
        else if (v && typeof v === 'object') return fn(v);
        return v;                
    },
    remove = key => ({ [key]:_ , ...o }) => Object.fromEntries(
        Object.entries(o).map(([k, v]) => [k, getValue(v, remove(key))])
    ),        
    array = [{ address: "asda", city: "asdasd", country: "1", description: { test: 123, name: 'name' }, id: { test: 152, idB: 'n' }, code: "asdas     ", test: 156 }];

console.log(array.map(remove('test')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.