Retrieve data from an array of objects nested within another object

Imagine a scenario where there is an object containing an array of objects.

let events = {
    "id": 241,
    "name": "Rock Party",
    "type": "party",
    "days": [
        {
            "id": 201,
            "day": "Monday"
        },
        {
            "id": 202,
            "dia": "Friday"
        }
    ],
}

The goal is to extract only the values under the key "day". For instance:

let days = ["Monday", "Friday"]

I attempted using Object.values(events.days[0]), however, the outcome was different:

[201, 'Monday']

Answer №1

let events = {
    "id": 241,
    "name": "Rock Event",
    "type": "event",
    "days": [
        {
            "id": 201,
            "day": "Monday"
        },
        {
            "id": 202,
            "dia": "Friday"
        }
    ],
};

let eventDays = events.days.map(x => x.dia || x.day);
console.log(eventDays);

This is the script that interacts with your information. However, I strongly believe that the property name should be either day or dia, not both simultaneously.

Answer №2

If dia is actually a mistake:

let days = [];
for (const party of allParties.days) {
   days.push(party.day);
}
console.log(days);

Answer №3

To easily achieve the desired outcome, utilize the Nullish coalescing operator (??)

partys.days.map((x) => x.dia ?? x.day);

let partys = {
  id: 241,
  name: "Rock Party",
  type: "party",
  days: [
    {
      id: 201,
      day: "Monday",
    },
    {
      id: 202,
      dia: "Friday",
    },
  ],
};

let days = partys.days.map((x) => x.dia ?? x.day);
console.log(days);

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

Establishing a Next.js API endpoint at the root level

I have a webpage located at URL root, which has been developed using React. Now, I am looking to create an API endpoint on the root as well. `http://localhost:3000/` > directs to the React page `http://localhost:3000/foo` > leads to the Next API end ...

Transferring a single dataset from a table to a pop-up modal using Angular

I am working on a table to display entries for a contest, extracted from a database using PHP and converted into a .json object for AngularJS and JavaScript. I want to add a modal feature so that when a "judge" clicks on an entry, they can view its details ...

Javascript generates a mapping of values contained within an array

In my current project, I am developing a feature that allows users to create customizable email templates with placeholder tags for content. These tags are structured like [FirstName] [LastName]. My goal is to brainstorm the most effective method for crea ...

What steps can I take to resolve the CSP errors I am experiencing?

I am currently working with NextJs@12 and I am attempting to set up CSP for my application. Unfortunately, I keep encountering errors in my console and I cannot figure out where I am going wrong. Below is the current policy that I have in my next.config fi ...

What steps can be taken to stop the page from refreshing and losing its state when cancelling navigation using the back and forward browser buttons in React-router v4.3?

I'm currently facing an issue with a page in which user inputs are saved using a react context object. The problem arises when a user navigates away from the page without saving their entries. I want to prompt the user to either continue or cancel, wh ...

Using data variables as arguments in the style section of Vue2

Suppose we have a data variable and I want to utilize this data variable for styling purposes. data() { return{ selected:{ index: 2 } } } <style> .parent-table >>> .table-row:nth-child(/* here I intend to use ...

What issue could be causing the JSON to array conversion to fail in an Android application?

My project's MainActivity (FSM, as known to many) is the only activity in my code. Here's a snippet of the code: public class MainActivity extends Activity { private static final String DEBUG_TAG = "HttpExample"; private static final Str ...

Utilize images stored locally in ReactJS

My path to the image is: ../src/assets/images/img_name.jpg" And my path to the file.js is: src/file_name.js If I include the following code in file.js: Import img_name from "../src/assets/images/img_name.jpg" Then reference the image pa ...

Exploring the possibilities of utilizing package.json exports within a TypeScript project

I have a local Typescript package that I am importing into a project using npm I ./path/to/midule. The JSON structure of the package.json for this package is as follows: { "name": "my_package", "version": "1.0.0&q ...

What steps do I need to take in order to develop a cross-platform icon using React Native

Currently in the process of creating a signup form, I am looking to incorporate icons that will display differently based on the platform being used. For example, when utilizing Ionicons, I would like the icon to appear as ios-person on iOS devices and m ...

Synchronizing Form Data in Angular 5: Pass and Populate Dropdowns between Components

I have developed a unique form (material dialog modal) that allows users to create an account. When the user clicks on the Register button, their created account should appear in a dropdown menu without redirecting or reloading the current page. I am facin ...

What is the best way to organize objects based on their timestamps?

I am faced with the task of merging two arrays of objects into a single array based on their timestamps. One array contains exact second timestamps, while the other consists of hourly ranges. My goal is to incorporate the 'humidity' values from t ...

Is the validation for the 'prop' property missing in props?

Seeking assistance with react's forwardRef feature. Currently encountering errors related to missing props validation in FadeContents. Is there a way to resolve this issue? It seems like the props need to be defined somewhere in order to be used withi ...

Create a single JSON object by searching through two collections in MongoDB

Is it possible for you to assist me in combining data from two collections into one JSON format? Users [ user_id, user_name, city_id ] [ { "name": "Anton", "user_id": 1, "city_id": 1 }, { "name": "Vasiliy", ...

The code within the then() promise resolver function will always execute, regardless of whether the promise succeeds or

After clicking a button, I trigger a vuex action which returns an axios promise from the store. In my component, I only want to reset form fields when the action is successful. However, currently the form fields are always reset, even if the promise fails. ...

Display contents from a JSON file

I need to extract unique locality values from a JSON file in Python, but my current code is only printing the first few entries and not iterating through all 538 elements. Here's what I have: import pandas as pd import json with open('data.json ...

When you use the useState object in NextJS, the context object may appear to be empty

I've encountered an issue while trying to pass a context object in NextJS that uses data from a useState hook. Strangely, the state variable and setState functions are undefined when consumed. It's puzzling because substituting a simple variable ...

What is the best way to extract information from a text file containing special characters?

fo = open("asset_database_2_16_0_Release.txt", "r") fo.seek(9) sep = fo.read(24 - 9) print (sep) I am looking to extract the data that lies between the strings {"code":" and _icon"," in the given text. {" ...

MulterError: Files must be uploaded to designated folders, found at wrappedFileFilter. Detected issue with 2 files

Initially, I want to express my apologies for any language mistakes in this message. I am currently facing difficulties with file uploads using Multer and Express. The issue arises when attempting to upload two files to separate directories; consistently ...

React and Rails are not playing nice when it comes to AJAX POST requests - all

I'm currently facing an issue while setting up this AJAX POST request in my react component to interact with my rails api controller. The browser console shows a 404 error and I am unable to trigger the pry debugger. react/src/pages/HomeIndex.js ge ...