Using JavaScript to access and retrieve a key/value pair from a nested object

In my JavaScript code, I am attempting to extract the Category property as an array from a nested key/value object structure. Here is an example of the data:

var data = [{key: "A", values:[{Category:"One", amount:2000},
    {Category: "Two", amount:2500},
    {Category: "Three", amount: 3000},
    {Category: "Four", amount: 3000}]
},
{key: "B", values:[{Category:"One", amount:2000},
    {Category: "Two", amount:2500},
    {Category: "Three", amount: 3000},
    {Category: "Four", amount: 3000}]
},
{key: "C", values:[{Category:"One", amount:2000},
    {Category: "Two", amount:2500},
    {Category: "Three", amount: 3000},
    {Category: "Four", amount: 3000}]
}]  

The desired output is to have an array like this:

["One","Two","Three","Four"]  

I have tried various methods to achieve this goal, with one attempt using a nested map function shown below. The variable data represents the above JavaScript object.

x = data.map(function(el) {return el.values.map(function(ele,i){return 
ele.Category;})})  

However, the current result is an array of arrays instead of a single array. Although I can manipulate the output to get the desired result, I believe there might be a more efficient solution.

[["One","Two","Three","Four"],["One","Two","Three","Four"],
["One","Two","Three","Four"]]  

If you have any suggestions or alternative approaches, they would be greatly appreciated. Thank you!

Answer №1

The first step is to flatten the array of arrays that is returned, and then utilize the Set function to eliminate any duplicate entries.

var data = [{key:"A",values:[{Category:"One",amount:2000},{Category:"Two",amount:2500},{Category:"Three",amount:3000},{Category:"Four",amount:3000}]},{key:"B",values:[{Category:"One",amount:2000},{Category:"Two",amount:2500},{Category:"Three",amount:3000},{Category:"Four",amount:3000}]},{key:"C",values:[{Category:"One",amount:2000},{Category:"Two",amount:2500},{Category:"Three",amount:3000},{Category:"Four",amount:3000}]}],
    x = data.map(v => v.values.map(c => c.Category)).reduce((a,b) => a.concat(b)),
    res = [...new Set(x)];

    console.log(res);

Answer №2

There's a clever solution to your problem that may not be immediately obvious. Your scenario is quite unique with duplicates that need to be removed. Utilizing an ES6 Set can efficiently handle this task, providing you with the desired result.

let data = [{key:"A",values:[{Category:"One",amount:2000},{Category:"Two",amount:2500},{Category:"Three",amount:3000},{Category:"Four",amount:3000}]},{key:"B",values:[{Category:"One",amount:2000},{Category:"Two",amount:2500},{Category:"Three",amount:3000},{Category:"Four",amount:3000}]},{key:"C",values:[{Category:"One",amount:2000},{Category:"Two",amount:2500},{Category:"Three",amount:3000},{Category:"Four",amount:3000}]}],
    set = new Set();
    data.forEach(val => {
        let v = val.values.forEach ( x => {
            set.add(x.Category);
        });
    });

    console.log(Array.from(set));

Answer №3

I am a big fan of Underscore.js.

const information = [
    {
        key: "A",
        values: [
            {Category: "One",   amount: 2000},
            {Category: "Two",   amount: 2500},
            {Category: "Three", amount: 3000},
            {Category: "Four",  amount: 3000}
        ]
    },
    ...
];

const categoriesList =
  _.special(
    _.compress(
      _.each(information, function (element) {
        return _.grab(element.values, 'Category');
      })
    )
  );

Answer №4

let information = [{id: "X", details:[{Type:"First", value:250},
    {Type: "Second", value:300},
    {Type: "Third", value: 450},
    {Type: "Fourth", value: 600}]
},
{id: "Y", details:[{Type:"First", value:200},
    {Type: "Second", value:350},
    {Type: "Third", value: 400},
    {Type: "Fourth", value: 500}]
},
{id: "Z", details:[{Type:"First", value:100},
    {Type: "Second", value:150},
    {Type: "Third", value: 200},
    {Type: "Fourth", value: 250}]
}
];


let answerArray = information.reduce(function(accumulator, element) {
    return accumulator.concat(element.details.map(y => y.Type));
}, [])

let finalResult = [...new Set(answerArray)]
console.log(finalResult);

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

Adjusting the CSS styling of my iframe element

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> $(document).ready( function () { $('#iView').load( function () { $('this').contents().find("html").css("background-image","none"); }); }); ...

Updating a particular attribute within a JSON object in a JSON Array using MySQL

Currently, my MySQL database includes a table with a JSON column that stores data as shown below: [{"id": 1, "value": 23.4}, {"id": 2, "value": 54.3}, {"id": 3, "value": 4.33}] I am looking to update the value property of all objects in this colum ...

Looking to integrate the date, month, and year selection tags into the inline format

The Edit User Profile page includes a Birthday field, which is currently displayed vertically. I am looking to change the layout so that the Birthday field appears horizontally. Here is the code I am using: Within visitors/edit.html.erb, <%= simple_f ...

Native JavaScript does not handle AJAX responses correctly

I'm facing an issue with my ajax call where the returned HTML works well on changes, but the Javascript that should perform actions based on clicks within the results is not functioning properly. Here is the ajax call: function update_order_shipp ...

Instructions on how to extract information from a JSON response in SharePoint in order to display a list of

This is my first time working with JSON, so please be kind and patient with me :) I am currently working on a website, which can be found at http://msdn.microsoft.com/en-us/library/jj164022(v=office.15).aspx Here is a sample of the JavaScript code I am u ...

How can I activate the copy function in jQuery?

I'm trying to figure out how to initiate a copy event using JavaScript or jQuery. I need to be able to simulate the copy event by clicking on a button, but I haven't been able to find a solution yet. I want to avoid using ZeroClipboard or any oth ...

The useState hook fails to update the value

Currently, I am using the onClick event to trigger setClickedMovieId. Additionally, I have implemented a useEffect hook to ensure that the state value is correctly set; however, it is logging out the default value of zero. The main goal here is to store t ...

Deleting a nested field in a document with NodeJS and MongoDB

I have a JSON object saved in a collection in the following format: [ { "username":"j", "pass":"t", "tracking": { "bettercallsaul":["1x1","1x2","1x3"] } } ] I am trying to remove the field "bet ...

Error: The datatable is requesting a parameter that is not recognized, specifically looking for parameter '4' in row

I encountered an error message while attempting to utilize a data table with the jQuery DataTables library. The system raised an issue stating 'Requested unknown parameter '4' for row 0.' <div class="container"> <%= render ...

multer - the file uploaded by the request is not defined

I've been working on an app with Node, Express, and multer for image uploads. However, after submitting the form, req.file is coming up as undefined. I've spent hours trying to troubleshoot this issue but haven't been able to pinpoint the pr ...

Sorting arrays with NaN values within objects will not result in a reordering when using the Array

I encountered a situation where I need to reorder items in an array based on the property minLVL of each object within the array. However, I have discovered that this reordering only works if the previous and next items have the required minLVL field. If ...

Utilizing synchronous API calls with jQuery's AJAX functionality

Is it possible to utilize jQuery's AJAX API for synchronous calls without using the async = false method? I need to retrieve data from a get request in a separate file, use that data in conjunction with a jQuery function, and then proceed with the res ...

Encountering AngularJS promise data parsing issues

I am trying to work with promises in AngularJS. However, I encountered an error while parsing the backend response in AngularJS. What could be the issue here? This is the HTML code: <div ng-app="clinang" ng-controller="pacientesCtrl"> <a ...

Storing PNG images as a ByteArray in Android can be accomplished by writing

After successfully reading an image file into a ByteArray, I am now wondering how to write it back. Specifically, I want to save the ByteArray as an image file in the file system, preferably in PNG format. Here is the code snippet I used to convert the PN ...

Locating the Smallest Value in an Array of Objects

Looking at an object with keys containing arrays of objects that each have a price value. The goal is to find and return the lowest price value. In this scenario, aiming to return the value 8. Wondering if using the reduce method would be the best approach ...

Tips for showing form values in pop-up boxes based on their unique identifiers

I am experiencing an issue with displaying posted values in a pop-up box. Specifically, when I click on "Book now", it only shows one set of id values for all entries. For example, if I click on the 1st row's "Book now" button, it displays the values ...

Guide to resolving Vue 2 and UIKit autocomplete template issues

I am encountering an issue with the Vue 2 + UIKit autocomplete feature. The template for the UIKit autocomplete is shown in the following code: <script type="text/autocomplete" v-pre> <ul class="uk-nav uk-nav-autocomplete uk-autocomplete-res ...

Vue-powered carousel having trouble rotating properly

I recently came across a carousel created using vanilla javascript and html. I attempted to convert it to Vue, but encountered some challenges. The carousel is supposed to dynamically pull images from a SharePoint list. However, in my version, the images a ...

Learn how to use Node.JS Express to write to a file from a static file by implementing server-side JavaScript

I am currently working on a node.js project where I can successfully write to a file from the app.js file. The app.js file starts the server and executes the content of index.html located in my public folder. However, I am facing an issue where I am unable ...

Add rows to the table dynamically and then execute the script

My table dynamically creates rows when a button is clicked, and there is an input box with an auto suggest script. The auto complete works fine on the default first box, but not on the dynamically added row. How can I make the auto complete script work o ...