Utilizing Lodash to Manipulate an Array of Objects

I'm attempting to simplify a complex structure.
After much simplification, I have managed to reduce it to the following:

[
  {'Cells':{'Results':[
                        {'Key':'ID','Value':123},
                        {'Key':'Color','Value':'Red'},
                        {'Key':'Direction','Value':'West'}
                      ]}},
  {'Cells':{'Results':[
                        {'Key':'ID','Value':456},
                        {'Key':'Color','Value':'Green'},
                        {'Key':'Direction','Value':'East'}
                      ]}}
]

My expertise in lodash is insufficient and I seek assistance in transforming the above into this format:

[
  {'ID':123, 'Color':'Red', 'Direction':'West'},
  {'ID':456, 'Color':'Green', 'Direction':'East'}
]

Note that the number of keys may differ for each object. Some objects may only include the ID, while others may have more than the three keys shown in the example.

Answer №1

If you were to write this in native JavaScript, you might utilize a pair of nested loops.

let data = [{ 'Cells': { 'Results': [{ 'Key': 'ID', 'Value': 123 }, { 'Key': 'Color', 'Value': 'Red' }, { 'Key': 'Direction', 'Value': 'West' }] } }, { 'Cells': { 'Results': [{ 'Key': 'ID', 'Value': 456 }, { 'Key': 'Color', 'Value': 'Green' }, { 'Key': 'Direction', 'Value': 'East' }] } }],
    simplified = data.map(function (item) {
        let object = {};
        item.Cells.Results.forEach(function (result) {
            object[result.Key] = result.Value;
        });
        return object;
    });

console.log(simplified);

Answer №2

Here is a Lodash approach to solving the problem:

const transformedData = _.chain(data)
    .map('Cells.Results')
    .map(res => _.zipObject(_.map(res,"Key"), _.map(res,"Value")))
    .value();

Answer №3

Here's a code snippet that could work for your situation, although some may argue that plain JavaScript is just as effective:

_.chain(array)
 .pluck('Cells')
 .pluck('Results')
 .map(function (value) { return _.object(_.map(value, _.values)); })
 .value()

Answer №4

Check out this different approach using lodash fp.

var result = map(compose(
  mapValues('Value'),
  keyBy('Key'),
  iteratee('Cells.Results')
))(data);

var data = [{
  'Cells': {
    'Results': [{
      'Key': 'ID',
      'Value': 123
    }, {
      'Key': 'Color',
      'Value': 'Red'
    }, {
      'Key': 'Direction',
      'Value': 'West'
    }]
  }
}, {
  'Cells': {
    'Results': [{
      'Key': 'ID',
      'Value': 456
    }, {
      'Key': 'Color',
      'Value': 'Green'
    }, {
      'Key': 'Direction',
      'Value': 'East'
    }]
  }
}];

var { compose, map, iteratee, keyBy, mapValues } = _;

var result = map(compose(
  mapValues('Value'),
  keyBy('Key'),
  iteratee('Cells.Results')
))(data);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.fp.js"></script>

Answer №5

Here is a different approach using map and reduce functions

    var startingArray=[
      {'Cells':{'Results':[
                        {'Key':'ID','Value':123},
                        {'Key':'Color','Value':'Red'},
                        {'Key':'Direction','Value':'West'}
                      ]}},
      {'Cells':{'Results':[
                        {'Key':'ID','Value':456},
                        {'Key':'Color','Value':'Green'},
                        {'Key':'Direction','Value':'East'}
                      ]}}
    ];

     function mergeObjects(accumulator,current){
       accumulator[current['Key']]=current['Value'];
       return accumulator;  
     }

     function extractResults(obj){
       return obj.Cells.Results.reduce(mergeObjects,{});
     }

     var modifiedArray=_(startingArray).map(extractResults).value();
     console.log(modifiedArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

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

Using user input to create conditional statements

I'm currently working on a project involving a textbot that outputs information in the console based on user input. It sounds simple, but I've encountered a frustrating problem that I can't seem to solve. There must be an easy fix for this i ...

Issue: Child Pages not found in Nuxt RoutingDescription: When navigating

Currently working on a Nuxt application that utilizes the WordPress REST API to fetch content. While my other routes are functioning correctly, I am facing challenges with nested pages. The structure I have implemented in my Nuxt app is as follows: pages ...

The variable in my NodeJS code is persisting across multiple requests and not being reset as expected

After setting up a project with the help of Typescript-Node-Starter, I have successfully created a controller and a route to call a specific function. import { Request, Response } from "express"; import axios from "axios"; import { pars ...

Tips for transferring values from one array to another array using JavaScript

I am attempting to incorporate values from the array below into another array [ {"criteriaName": "CRITERIA 1"}, {"criteriaType": "Dependent"}, {"table": "Table1"}, {"column": "Column1"}, {"joinType": "OR"}, {"o ...

Laravel: The current configuration does not support the experimental syntax 'classProperties' at this time

When compiling my javascript files using npm run dev, I encountered a warning in my resource/app.js file where I require my custom validation script. The warning stated the following: Module build failed (from ./node_modules/babel-loader/lib/index.js): Syn ...

Retrieving information from a nested .then callback

Summing it up briefly, I've been diving into the depths of learning JavaScript for a while now. After hours and hours of relentless Googling, I find myself stuck with an issue that eludes resolution, pointing to my flawed approach. The objective at h ...

Trouble disabling specific days of the week in Meteor's Bootstrap3 datetimepicker

Currently, I'm utilizing bootstrap 3 within a meteor project and I have a requirement to deactivate most of the days of the week in a datetime picker. Although the other options I've configured appear to be functioning correctly, the daysOfWeekD ...

Merging JSON Array of Objects from Separate Http Services in Angular 8

I am currently working on a new Angular 8 project where I need to retrieve JSON data from two different services in my component. Both sets of data are arrays of objects. My goal is to merge the objects from these arrays and then post the combined data bac ...

Encountering issues with $.AJAX post in JavaScript, while successful in Advanced Rest Client

My JavaScript code is facing an issue when trying to communicate with the HttpPost service. Interestingly, I can access the same endpoint using the "Advanced Rest Client Application" for Chrome without any problems. However, when I execute my code in the C ...

Exclude a specific tag from a div in JavaScript

I need help selecting the text within an alert in JavaScript, excluding the <a> tag... <div id="addCompaniesModal" > <div class="alertBox costumAlertBox" style="display:inline-block;"> <div class="alert alert-block alert- ...

The AJAX success callback function failed to execute in cases where the dataType was set to JSONP during Cross domain Access

type = 'math'; var ajurl = "sample.com&callback=myhandler"; var datas = "cateid=" + cateid + "&type=" + type + "&pno=" + pno + "&whos=" + whos; $.ajax({ type: "GET", url: ajurl, data: datas, contentType: "application/json; ...

What is the best way to incorporate the 'autoskip' functionality into chartjs?

Click here for an example I've been attempting to utilize the autoSkip functionality outlined in the documentation for chart.js: Visit this link for more information on autoSkip The current issue I'm facing is that my x-axis labels are o ...

What is the best way to retrieve all arrays within a JSON object?

After successfully sending a JSON object from the view to HTML via AJAX in Django, it looks like this: json: Object name1: Array[2] name2: Array[2] age: '18' class: 'CLS01' phone: '' code: 'SV01' Now, I am trying t ...

Mocha maintains the integrity of files during testing

After running a unit test to update a config file, I noticed that the file was altered. My initial thought was to use "before" to cache the file and then restore it with "after". mod = require('../modtotest'); describe('Device Configuratio ...

Refine the JSON data to only include the values you need

I've been spending a considerable amount of time on this challenge, but I'm facing difficulty in solving it. The issue at hand is that I have a JSON file that I am fetching from a URL, and my objective is to create a filter that displays only nam ...

What is the method for importing the merge function from "lodash/merge" in TypeScript?

When using ES6, it's possible to import only a single function from a library in order to reduce the overall bundle size. For example: import merge from "lodash/merge" But in TypeScript, the statement above can trigger a compile error: Cannot find m ...

Warning triggered Grunt cancellation

I've successfully installed "npm" on my local machine. When it comes to installing grunt in my Gruntfile.js directory, I follow these steps: npm install grunt npm install -g grunt-cli grunt watch Although the tasker is up and running, I en ...

Retrieve the value from a dictionary in Swift by utilizing an integer variable

I am in the process of developing an iOS application and I am facing a challenge with accessing a specific value in a Dictionary by using Array(). Within my dictionary, there is an array that contains various structs. let array = [(key: "S", value: [Thun ...

What is the most effective way to append a new key-value pair to the end of an OrderedMap?

Possible duplicate: Adding Items in OrderedMap using Immutable.js Utilizing redux store and Immutable js with OrderedMap. Structure of Redux store: { "app": { "name": "Test app", "dataPack":{ "chemID": "aaaa", ...

Creating an interactive dropdown menu in react.js

For a project I'm working on, the user can input data that is then sent to a MongoDB instance. There's also a search bar where users can retrieve the data and select a specific ID to view all corresponding document information in text fields. ht ...