Manipulating Arrays in JavaScript: Techniques for Extracting Values Buried in Nested Objects

I am working with an array of objects that contain multiple "Book" objects with dynamic keys. My goal is to filter the objects in the array to only include those that have at least one new "Book" object.

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},
  },
]

The filtered array should only consist of the first and last elements from the original array.

Expected filtered array:

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

I have attempted using filter and map, but I am struggling on how to identify and return the objects with new books within the filter function.

Answer №1

If you're looking for a solution similar to this:

arr.filter((o) => Object.values(o).some((b) => b.isNew))

Is it certain that your array will always contain keys like id and bookwxyz? If not, it might be necessary to verify the values to ensure they are not undefined

You can also validate the key explicitly using Object.entries along with a regular expression:

arr.filter((o) => Object.entries(o).some(([key, value]) => /book\d{4}/.test(key) && value.isNew))

Answer №2

You can implement a solution using Array#some in conjunction with Object.values.

const data = [ { 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}, }, ];
const result = data.filter(obj=>Object.values(obj).some(({isNew})=>isNew));
console.log(result);

Answer №3

let collection = [{id:"123",book1242:{isNew:!0},book9023:{isNew:!1}},{id:"123",book0374:{isNew:!1},book9423:{isNew:!1}},{id:"123",book8423:{isNew:!1},book9023:{isNew:!1}},{id:"123",book6534:{isNew:!0},book9313:{isNew:!1}}];

const result = collection.filter(item => {
  for(const [key, value] of Object.entries(item)){
    if(key.substring(0,4) === 'book' && value.isNew === true){
      return item;
    }
   }
});

console.log(result);

Answer №4

 const sortedArray = []
  data.forEach((element, index) => {
         let objValues = Object.values(element);
         objValues = objValues.filter((el) => typeof el == 'object' && el.isNew == true);
if(objValues.length) sortedArray.push(data[index])
     })

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

Capture a snapshot with Protractor using the Jasmine2 Screenshot Reporter

The Protractor configuration file includes 2 custom reporting options: one for logging and the other is the protractor-jasmine2-screenshot-reporter. However, only a blank white screen is displayed when generating a screenshot png. Below is the code snippet ...

Is it necessary for the Jquery Component to return false?

I'm currently working on developing a jQuery module using BDD (Behavior-driven development). Below is the code snippet for my component: (function($) { function MyModule(element){ return false; } $.fn.myModule = function ...

encountering an issue with server-side rendering of React causing an error

Node.js has been a bit of a challenge for me, especially when it comes to working with react and express. I have been struggling to find comprehensive tutorials and troubleshooting resources, leading me to ask minimal questions in the correct manner. While ...

Unable to assign a value to a dropdown using Angular.js and PHP

I am encountering a slight issue with setting the data as a selected value in a dropdown after fetching it from the database. Below is an explanation of my code. plan.html: <div class="input-group bmargindiv1 col-md-12"> <span class="input-g ...

Svelte language switcher experiencing technical difficulties

Currently delving into Svelte 3, I embarked on a project intended to be shared on GitHub in English. However, I realized that some of my friends do not speak English. To accommodate different language preferences, I decided to create a language switcher. H ...

Tips for updating iframe source without refreshing the iframe?

I am facing an issue with two frames where I need to copy the content from the first frame (myframe) to the second frame (myframe2) using JavaScript. The challenge is that when I set the "src" attribute for myframe2, it causes a reload of FrameSecond. Is ...

Eliminate the alert message that appears when dynamically rendering a React styled component

When checking the browser console, I noticed a warning that reads as follows: react_devtools_backend.js:3973 The component styled.div with the id of "sc-dmRaPn" has been created dynamically. You may see this warning because you've called sty ...

`The logo does not dim when the popup is displayed`

I'm currently experiencing an issue with pop-ups on my page - when they appear, they create a shade over all elements of the page except for my two logos and are displayed with a border around them. Here's what my page looks like before the popu ...

Generating instances using TypeScript generics

Looking to create a factory for instantiating classes with generics. After checking out the TypeScript docs, everything seems to work as expected. Here's a simplified version of how it can be done: class Person { firstName = 'John'; ...

Exploring the connections between PHP, JavaScript, JSON, and AJAX

While this question may lean more towards conceptual understanding rather than pure programming, it is essential for me to grasp how these mechanisms interact in order to code effectively. My current knowledge includes: 1) PHP as a programming language ...

How can I set a background image to automatically adjust to the width of the window, be full height, allow for vertical scrolling, and

How can I set a full-screen background image that adjusts to the body width without horizontal scrolling, maintains height proportionate to width, and allows for vertical scrolling? Here is my current code: html, body { margin: 0px; padding: 0px; } bo ...

Switching from using ngRouter to ui-router is a common

After purchasing an angularjs template for my application, I noticed that ngRouter was used instead of ui-router, which I am more comfortable with. So, I decided to switch to ui-router and update all the routes. However, I encountered some extra code in my ...

Encountering a "Connection Refused" error when attempting to test a React and Express application

Currently, I am developing an order system using React for the frontend (port 3000) and Express for the backend (port 3001). Everything functions perfectly when tested on the same MacBook that hosts the node project. However, when testing it on a differen ...

Why is the body the last element in Angular modules arrays?

I have a question regarding architectural practices. When defining an Angular module, one common approach is to do it like this: angular.module('app', []) .controller('Ctrl', ['$scope', function Ctrl($scope) { //body.. ...

Create a custom VueJS component by utilizing an npm package

Looking to navigate around X-frame restrictions? You can check out this npm package: https://www.npmjs.com/package/x-frame-bypass To make it work, include the following tag within your HTML: <iframe is="x-frame-bypass" src="https://example.org/">& ...

The jQuery functions properly offline, but fails to load when connected to the

I am encountering an issue with the following script: <script type="text/javascript"> $.getJSON("http://api.twitter.com/1/statuses/user_timeline/koawatea.json?count=1&include_rts=1&callback=?", function(data) { $("#headertweet") ...

Issue: ENOENT error occurred during execution on Docker Container due to missing file or directory '/root/.aws/credentials'

click here for image description While the app runs normally locally, attempting to run it in a Docker container results in an error displayed on the screen. This is my Docker file: FROM node:14.0.0 WORKDIR /app ARG DATABASE_URL ARG AWS_REGION ARG CLIENT_ ...

Reading and decoding JSON data using AJAX

Upon viewing the console, I receive the JSON data in the following format: [Object] 0: Object address: "soham" region: "soham" relevanceScore: "4" startDate: "2015-05-10" subscriptionType: "1" verificationStatus: "1" __pro ...

Why does the del command delete the parent folder as well?

I am looking to remove all files within the ./dist/* directory while leaving the ./dist folder itself untouched (it should be empty once the task completes). const del = require('del'); gulp.task('clean:dist', function(cb){ del([ ...

Attempting to retrieve data from a table containing 100,000 records, the execution time has surpassed

Each member in our database has multiple records. My goal is to calculate the sum of a specific column for each user and find the highest/lowest value from another column. With over 100k records in the table, some users may have more than 2k entries. I at ...