Filtering an array of nested objects in JavaScript: A step-by-step guide

Let's say I have an array structured like this:

const arr = [
  {
    id: '123',
    book: {isNew: true}
  },
  {
    id: '123',
    book: {isNew: false}
  },
  {
    id: '123',
    book: {isNew: false}
  },
  {
    id: '123',
    book: {isNew: true}
  },
]

My goal is to filter the array and only retrieve objects where the book object has isNew set to true.

I initially tried the following approach:

arr.filter(obj => {
  // Use a forEach loop to check for new books
}

However, since a forEach loop doesn't return any values, that method didn't work as expected.

UPDATE

It seems my explanation was somewhat unclear. In each object of the array, there can be multiple "Book" objects with dynamic keys. I want to identify objects that have at least one "Book" object with isNew set to true.

For example:

const arr = [
  {
    id: '123',
    book1242: {isNew: true},
    book9023: {isNew: false},
  },
  {
    id: '123',
    book0374: {isNew: false},
    book9423: {isNew: false},
  },
  {
    id: '123',
    book8423: {isNew: false},
    book9023: {isNew: false},
  },
  {
    id: '123',
    book6534: {isNew: true},
    book9313: {isNew: false},
  },
]

Thus, after filtering, my resulting array should contain the first and last elements from the original array.

Answer №1

What do you think of this approach?

arr.filter(({ book: { isNew } }) => isNew)

I am utilizing a data structure to extract the isNew property and only return the TRUE value.

UPDATE :

The syntax ({ book: { isNew } }) is an alternative way to express

arr.filter((object) => object.book.isNew)

UPDATE :

The initial query was related to dynamic [key] and I have proposed 2 solutions Solution 1 -

arr.filter((item) => {
  for (const key of Object.keys(item)) {
    const { isNew } = item[key]
    if (typeof isNew === 'boolean') return isNew
  }
})

In this solution, I am filtering and iterating through each key to check for a property with the key [ isNew ]
and returning it if found

Another possible implementation:

arr.filter((item) => {
  for (const key of Object.keys(item))
    if (item[key].hasOwnProperty('isNew')) return item[key].isNew
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my difficulty in locating an HTML element using jQuery/JS string interpolation?

In my project, I have a set of div blocks each identified by a unique numerical id. For instance: https://i.sstatic.net/lYod8.png One of the tasks in my project is to select the 29th element following a specific chosen element. For example, if I choose t ...

React - the method runs correctly when triggered by state changes, but runs twice when the parent component's state changes

As I work on constructing a page that requires data to be initialized upon mounting, updated based on responses from a websocket server triggered by a button click event, and the ability to disable and re-enable the button with a countdown for the user. M ...

What is the most effective way to trigger a jQuery datatable event after updates, rather than before?

After the default datatable updates like searching and sorting are finished, I am looking to update DOM elements. The issue is that the event listening currently fires before the actual sort or search completion. My goal is for my code to run after the s ...

Obtaining a variable from within a function in Angular.js

Utilizing a service, I am retrieving data from the server through this function: LeadsSrv.async().then(function (d) { results = d.data; }); The goal is to access the results outside of this function and assign them to the scope like so: $scope.All_L ...

What is the reason for Cloud Firestore's realtime database fetching all items?

Currently, I am developing a project with vuejs and I am facing an issue where I need to fetch only the last created item from Firestore's realtime database. However, when I execute the following code snippet, it retrieves all items from the database ...

Angular 4 in combination with ngx-datatable is showing a 404 error for the @swimlane/ngx-datatable package

Just starting out with Angular and I kicked things off by running this command: git clone https://github.com/angular/quickstart appName I've made the upgrade to Angular 4 and everything seems to be in order. Here's the output I got after running ...

Is there a way to determine if any word within a given text is present in an array?

Imagine you have the following full text: var nation = "Piazza delle Medaglie d'Oro 40121 Bologna Italy" And a given array like: ["Afghanistan", "Italy", "Albania", "United Arab Emirates"] How can we verify if the exact word Italy within that ent ...

What is the best way to create a text input that is both secure and non-editable?

While I am aware of the <input type="text" readonly /> possibility, it is not entirely secure. For example, if there is an input field that must remain uneditable by users, making it "readonly" can still be bypassed by inspecting the code and remov ...

Creating a table using Ng-repeat in AngularJS: A Step-by-Step Guide

I'm trying to figure out how to create the table below using ng-repeat. Unfortunately, I don't have permission to modify the json structure so I need to work with it as is. Here's my json: $scope.carCollection = { 'Toyota': [ ...

Utilizing an AngularJS factory to retrieve JSON data from the server

I have a large JSON object in my controller that I want to move to a separate file. Currently, this is how I'm approaching it: myApp.controller('smController', ['$scope', function($scope) { ... var stadtmobilRates = { cla ...

"Using JavaScript to initiate a popup window that displays a specific destination link

Whenever I view this code, the iframe popup automatically opens. But I want the iframe to open only when I click the "click me" button. Can someone please assist me with this? I believe it's a simple trick, but as a JavaScript amateur, I am struggling ...

Dynamic allocation and the use of arrays/pointers are causing a segmentation fault

Exploring the fundamentals of dynamic memory allocation and pointers has been an exciting challenge for me. Initially, I created a basic program that sorted 5 names and scores in descending order using selection sort. Now, my task involves revisiting this ...

Access the Ajax response and store it in a JavaScript variable

I've successfully created a script that inserts data into an MySQL database using a modal and AJAX. However, I'm having trouble retrieving the response to complete an input field. Below is my current script: $.ajax({ url:"insertar_cl ...

Issue with jQuery: Function not triggered by value selection in dynamically created select boxes

I am in need of some assistance with my code that dynamically generates select drop down menus. I want each menu to trigger a different function when an option is selected using the "onchange" event, but I am struggling to implement this feature. Any hel ...

Struggles with PHP and the Challenges of Nested Arrays

I'm currently facing challenges working with nested arrays using json_decode(). Specifically, I'm attempting to extract a list of team names. Here is the array in question: http://pastebin.com/eMqMcucN Upon examining the array, it is clear that ...

Troubleshooting AngularJS UI Router -> Issue with resolution when implementing ui-sref

I have successfully set up a JSON file containing my ui-routes. However, I am encountering difficulties when using the Link functionality. I have managed to use it for the following state: { "name": "home", "url": "^/home", "abstract": false, ...

Identify alterations in django-bootstrap-datepicker-plus through JQuery

I am having an issue with the django-bootstrap-datepicker-plus package. I want to trigger an alert when the date changes, but it seems that JQuery is not detecting any modifications to the date field. Following the guidance in this question about detectin ...

Using `preventDefault()` will also block any text input from being entered

Note: I am looking for a way to clear the text box using the enter key after typing some text. My apologies for any confusion caused. Update 2: The missing event parameter was causing all the issues. I feel like a failure as a programmer. I am trying to ...

Learn how to automatically navigate to another page upon successfully creating an account and setting a value in the Firebase database

I am working on a system where, after successfully creating an account and setting a value in Firebase database, the user will be redirected to another page. Currently, I have managed to navigate to the next page but I am facing an issue with setting the ...

Ways to update a component's state by clicking a button located on a different component

Seeking help with changing a parent state value when clicking a button. Although there are numerous similar queries out there, I'm really struggling to grasp the concept. I've attempted lifting the state up but haven't quite nailed it yet. ...