Remove object property from the nested object in the array

I have the following array of books. I want a write a function that receives the target book and the language, removes that book (key, value) from the nested object and returns the new array.

let books = [
  {
    language: 'spanish',
    books: {
      book_1: 'book1_spanish',
      book_2: 'book2_spanish',
      book_3: 'book3_spanish'
    }
  },
  {
    language: 'italian',
    books: {
      book_1: 'book1_italian',
      book_2: 'book2_italian',
      book_3: 'book3_italian'
    }
  }
];

let targetBook = { book_1: 'book1_spanish' };
let language = 'spanish';

I am stuck at looping over the nested object.

function removeTargetBook(lan, target) {
  return books.map(book => {
    if (book.language == lan) {
      Object.values(book).map(value => {});
    }
  });
}

It should return the same array without book_1: ‘book1_spanish’. This is my stackblitz: https://stackblitz.com/edit/js-yxcrbq

Thanks.

Answer

You want to be using the delete operator.

I took the liberty of expanding on your code a little to show you how using the key of the object in a forEach loop is more efficient than doing a key / value pair comparison. Also note that I am leaving the original books object intact, this is important for unit testable code and data integrity, but you can change/implement as you need.

let books = [
  {
    language: 'spanish',
    books: {
      book_1: 'book1_spanish',
      book_2: 'book2_spanish',
      book_3: 'book3_spanish'
    }
  },
  {
    language: 'italian',
    books: {
      book_1: 'book1_italian',
      book_2: 'book2_italian',
      book_3: 'book3_italian'
    }
  }
];

let targetBook = { book_1: 'book1_spanish' };
let language = 'spanish';
let target = Object.keys(targetBook)[0]; // we only need the 'key' of the targetBook
let result;

function removeTargetBook(books, lan, target) {
  books.forEach(elem => { // some instead of forEach works here as well
    elem.language === lan && (delete elem.books[target]);
  });
  
  return books;
}
// multiple tests for correctness
result = removeTargetBook(books, language, 'fool proof test');
console.log(result);
result = removeTargetBook(books, language, target);
console.log(result);
result = removeTargetBook(books, language, 'book_2');
console.log(result);
result = removeTargetBook(books, language, 'book_3');
console.log(result);