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

AXE - Asp Xtreme Evolution - A cutting-edge JSON parser designed specifically for classic ASP development

Is there anyone who has successfully used this and got it to work? I'm encountering some issues with a JScript error and I'm unsure about how to resolve it. For more information on the product, you can refer to the following links. It's a J ...

Using a conditional statement in a JavaScript loop

Here is the data I have: companyList: [ { company_name: 'company1', item: 'item1' }, { company_name: 'company1', item: 'item2' }, { company_n ...

Retrieving information from a database by employing AngularJS with the assistance of PHP

I am a beginner in using AngularJS and I am trying to retrieve data from a database using PHP. Here is the code I have tried: <html> <head> <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.2 ...

How can we prevent MOXy from displaying the data type in JSON output when marshalling a List<?>?

Is there a way to prevent the type from being displayed when marshalling a List<?>? For example, when marshalling a List<?>, the result is [{"type" : "person","id":"1"},{"type" : "person","id":"2"}] }, and it also includes the type="Person" in ...

Executing a function with arguments within a separate function

I've been working on creating a scheduler function that can randomly call another function with parameters. Here's the JavaScript code I have so far: function scheduleFunction(t, deltaT, functionName) { var timeout; var timeoutID; ...

The onbeforeunload event is activated in the parent page when it is specified in the child page

Seeking a way to activate the window.onbeforeunload method when a user attempts to refresh the browser, and display a message to prompt them to save their current work before leaving. I am currently working on an AngularJS application. Here is the URL of m ...

Inverting the order of a list in ng-repeat

Currently, I am dealing with an array that I am rendering using ng-repeat, but I would like to reverse this list. In the past, I have used a filter based on a solution I found here: angular ng-repeat in reverse However, I am now encountering an error: "Ty ...

Issues with retrieving data from Firestore and storing it into an array in a React

Struggling to fetch data from my firestore and display it on the webpage. Despite trying all possible solutions and searching extensively, I am unable to get it working. When using the code below, nothing appears on the website. However, if I switch to th ...

How can jq be used to compactly format specific fields?

Is jq the optimal solution for formatting arbitrary JSON? cat my.json | jq . is effective for pretty-printing JSON, but it can expand each field on separate lines. However, what if certain fields are repetitive, like a list of points? How can we format m ...

Learn how to extract data from a JSON array in ASP.NET

Looking for guidance on parsing a JSON array in ASP.NET using C#. Below is a sample JSON data that needs to be parsed: [ { "idvisit":"3", "iduser":"shoaibshakeel", "idpage":"1", "pagetime":"0" }, { "idvi ...

Troubleshooting a problem with the skybox texture in Three.js

I am currently experimenting with creating a basic Skybox using Three.js, but I've encountered an issue where the texture I'm applying to the cube is only visible on the outside and not on the inside. Below is the code for my skybox: const path ...

Even after setting [attr.disabled]="false" in Angular, the Textarea still remains disabled

I am currently utilizing ngModel for a textarea, and I would like to be able to enable and disable the textarea based on a certain condition. Even though I have bound it correctly and the value is changing to [attr.disabled]="false", the textarea remains d ...

Breaking Long Strings into Multiple Lines Using React Material UI Typography

Currently, I am working with ReactJS and incorporating MaterialUI components library into my project. However, I have encountered a problem with the Typography component. When I input a long text, it overflows its container without breaking onto a new lin ...

Attempting to assign the object retrieved from the interface as the new value for window.location.href

I encountered an issue where the error message Type MyInterface' is not assignable to type 'string' popped up. Although I comprehend the problem, finding a suitable solution has proven to be challenging. MyInterface solely returns one item, ...

Does Node.js offer a solution or module for converting Google Map polylines into a PNG image without the need for rendering HTML?

I'm attempting to generate a PNG image of polylines on a Google Map using Node.js on the backend without utilizing any view engine. I attempted to use the "webshot" Node.js package, but it was unable to save the polylines on the Google Map. app.get( ...

construct a table utilizing JSON information

If I have data returned from an ajax call that needs to be processed, a table like the following needs to be created: ID NAME Object Type ============================================== 1 SWT-F1-S32-RTR-1 Network Switch 2 ...

Failure to load image logo when refreshing the page

There's something peculiar happening in my App.vue. Imagine I have a route link, let's say it's localhost/tools or any similar route. The logo image will display on this route. Take a look at the image here https://i.stack.imgur.com/6HaXI.p ...

Is it possible to link the value of an input[range] to an array?

I want to create an array called arr dynamically with a length based on the value of ng-model (numberFloor) from an input[type=range]. var app = angular.module("houseBuilder", ['ngSanitize']); app.controller('myCtrl', function($scop ...

Tips for displaying animations only the first time using HTML and CSS:

Upon the initial visit to my website, a captivating animation introduces itself with the words "Hello. I'm Bob" as it gracefully fades into view. Navigating through the menu bar allows users to explore different sections of the site. However, there ...

Find and delete an item from a JSON array

Currently, I am attempting to locate a specific object within a JSON array and remove it. The structure of my JSON array containing objects is as follows: var data = [{ {id: "1", name: "Snatch", type: "crime"}, {id: "2", name: "Witches of Eastwic ...