Home > OS >  Javascript filter array object inside non-array object
Javascript filter array object inside non-array object

Time:10-19

I have an object like this:

var obj = {name: 'Lesson I', author: [{name: 'Thomas', age: '40'}, {name: 'Richard', age: '33'}]}

I tried to filter the object to show only the author with age above 35. This is what I expected:

var obj = {name: 'Lesson I', author: [{name: 'Thomas', age: '40'}]}

However since the array is inside a non-array object, I cannot use filter() yet. How to approach this?

CodePudding user response:

This is helpful in case you have more than one variable that keeps the same:

var obj = {name: 'Lesson I', author: [{name: 'Thomas', age: '40'}, {name: 'Richard', age: '33'}]}


obj = {
   ...obj,
   author: obj.author.filter( x => x.age >= 35)
}


console.log(obj)

Although I recommend keeping the original obj and create a new one for the filtered obj:

var obj = {name: 'Lesson I', author: [{name: 'Thomas', age: '40'}, {name: 'Richard', age: '33'}]}


const above35 = {
   ...obj,
   author: obj.author.filter( x => x.age >= 35)
}


console.log(obj,"and",above35)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

CodePudding user response:

obj.author = obj.author.filter(checkAge);  // this will return an array with 1 object.

function checkAge(author) {
  return author.age >= 35;
}

CodePudding user response:

One simple way would be like this:

var obj = {
  name: "Lesson I",
  author: [
    { name: "Thomas", age: "40" },
    { name: "Richard", age: "33" },
  ],
};
const result = obj.author.filter((ob) => ob.age > 35);

obj.author = result;
console.log(obj);

CodePudding user response:

One way...declare a new object with each key/value of the original object, but filter() the author value:

let obj = {name: 'Lesson I', author: [{name: 'Thomas', age: '40'}, {name: 'Richard', age: '33'}]};

let obj_old_authors = {
  name: obj.name, 
  author: obj.author.filter(author => 35 < author.age)
};

console.log(obj_old_authors);

  • Related