What is the method to convert a single object into an array of multiple objects?

Is there a way to convert this into an array of objects that are ordered based on another array's keys?

{
  tom: 11,
  jim: 22,
  jay: 13
}

Here are some input -> output examples:

['jim', 'tom', 'kim', 'jay'] ->

[{jim: 22}, {tom: 11}, {jay: 13}]

['may', 'jay', 'tom', 'jim'] ->

[{jay: 13}, {tom: 11}, {jim: 22}]

I am looking for a solution, preferably using a one-liner in lodash. How can I achieve this transformation?

Answer №1

Here is a JavaScript function that can help you achieve your desired outcome.

function filterValues(sourceObj, keys) {
    let filteredValues = [];

    // Check for valid inputs
    if (!sourceObj || !keys) { return filteredValues; }

    for (let i = 0; i < keys.length; i++) {
        if (!sourceObj.hasOwnProperty(keys[i])) { continue; }     
        let item = {};
        item[keys[i]] = sourceObj[keys[i]];
        filteredValues.push(item);
    }

    return filteredValues;   
}

Testing the Function:

let testObject = { john: 25, sarah: 30, emma: 22 };
let testKeys1 = ['sarah', 'john', 'david', 'emma'];
let testKeys2 = ['lucy', 'emma', 'john', 'sarah'];

let result1 = filterValues(testObject, testKeys1);
console.log(JSON.stringify(result1));

let result2 = filterValues(testObject, testKeys2);
console.log(JSON.stringify(result2)); 

View on JSFiddle

Answer №2

In the case that the object is referred to as obj and the list of keys to search for is named keys:

_.zip([keys, keys.map(x => obj[x])]).filter(([k, v]) => v).map(x => _.fromPairs([x]))

Alternatively, if order does not matter, there is another approach:

_.toPairs(obj).filter(([k, v]) => _.include(keys, k)).map(x => _.fromPairs([x]))

Answer №3

To convert the object into an array of key-value pairs using lodash, you can utilize the lodash#toPairs method. Then, wrap each pair with another array by using lodash#chunk. Finally, map each item to form the pairs into an object using lodash#map and iterate through them using lodash#fromPairs.

var result = _(data).toPairs().chunk().map(_.fromPairs).value();

var data = {
  tom: 11,
  jim: 22,
  jay: 13
};

var result = _(data).toPairs().chunk().map(_.fromPairs).value();
  
console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

An alternative Vanilla JS ES6 solution involves using Object#keys to extract an array of keys from the object. Then, use Array#map to associate each key with its corresponding value in a new object.

var result = Object.keys(data).map(key => ({ [key]: data[key] }));

var data = {
  tom: 11,
  jim: 22,
  jay: 13
};

var result = Object.keys(data).map(key => ({ [key]: data[key] }));
  
console.log(result);
.as-console-wrapper{min-height:100%;top:0}

If your browser doesn't support ES6 features, you can use the following modified version:

var result = Object.keys(data).map(function(key) {
  var obj = {};
  obj[key] = data[key];
  return obj;
});

var data = {
  tom: 11,
  jim: 22,
  jay: 13
};

var result = Object.keys(data).map(function(key) {
  var obj = {};
  obj[key] = data[key];
  return obj;
});
  
console.log(result);
.as-console-wrapper{min-height:100%;top:0}

Answer №4

For a quick one-liner solution to this problem, you can achieve it without relying on lodash. All you need are simple filter and map functions. However, if you prefer, you can also utilize lodash.

// Here is your source object 
var keys = {
  tom: 11,
  jim: 22,
  jay: 13
}

Let's assume you have two arrays:

var input1 = ['jim', 'tom', 'kim', 'jay'];
var input2 = ['may', 'jay', 'tom', 'jim'];

Now, for the solutions:

// For the first input
input1.filter(s => keys[s]).map(s => ({[s]: keys[s]}));
// For the second input
input2.filter(s => keys[s]).map(s => ({[s]: keys[s]}));

Below is a working snippet for you:

var keys = {
  tom: 11,
  jim: 22,
  jay: 13
}

var input1 = ['jim', 'tom', 'kim', 'jay'];
var input2 = ['may', 'jay', 'tom', 'jim'];

var output1 = input1.filter(s => keys[s]).map(s => ({[s]: keys[s]}));
var output2 = input2.filter(s => keys[s]).map(s => ({[s]: keys[s]}));

console.log("Output1: ", JSON.stringify(output1));
console.log("Output2: ", JSON.stringify(output2));

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

Is it possible to switch the linter in grunt.js to jslint instead?

Is it feasible to switch the linter used by grunt.js from jshint to jslint, considering that I am more accustomed to using jslint over jshint as the default linter? ...

Issue with Chart JS: Firefox is reporting that the 'Chart' is not defined

As a newcomer to Chart JS, I am currently utilizing it in Angular JS version 1.5.3 with Chart JS version 2.1.4. Below is the code snippet I am working with: var myChart = new Chart(ctx, { type: 'line', data: { labels: dates, datasets: [{ ...

How can the executable path for Firefox be specified in Nightwatch?

I've been using nightwatch to run tests on both Chrome and Firefox with great success. While everything runs smoothly on Chrome, I'm facing an issue when trying to run tests on Firefox on my personal machine. Currently, due to Marionette's ...

Discord bot that combines the power of discord.js and node.js to enhance your music

I am currently working on a Discord bot designed to play music in voice chat rooms. However, I am facing some issues with properties. Whenever I try to launch the bot using "node main", I encounter the following error message: "TypeError: Cannot read prope ...

Steps to display a full-page loader/spinner prior to the completion of loading a React application

What is the best way to create a full-page loader/spinner that will be displayed until a React (or other JS-based framework) app is fully loaded? By "fully loaded," I mean when the browser's spinner stops spinning. I have experience creating loaders ...

What is the best way to create a "check all" feature in React using child components?

I have come across a few questions here that somewhat address the issue, select all managed state of controlled checkboxes but none of them provide a solution for rendering a component with a checkbox. What I want is something like this, render: funct ...

Email replay feature

Having an issue with my email validation function. I found the code I'm using here: Repeat email in HTML Form not the same. Why? The problem I am facing is that if you incorrectly enter your email in the first input "eMail" and correctly in the seco ...

Deployment to Amazon Amplify encounters failure when using Next JS

I've been encountering continuous failures while trying to deploy an SSG app on Next JS. The build consistently fails, and I'm met with an error message. Despite following the deployment documentation for SSG sites on Amazon diligently, the error ...

Observing model property changes in Swift with didSet isn't working as expected

Using a didSet to establish an array of keys from a dictionary in order to prevent duplication when accessing the array to populate collection view cells. The didSet is intended to trigger when a Cafe object is updated, but it is not working as expected. ...

"Exploring the world of arrays and looping in

Can someone assist me with this issue? I am currently stuck in JS Arrays & Loops and I can't understand why it's not returning "0" when the function is empty. function sumArray (numbers) { // your code var numbers = [1, 2, 3, 4]; if (nu ...

Having trouble resolving errors encountered while running the `npm run build` command, not sure of the steps to rectify

I am currently working on my first app and attempting to deploy it for the first time. However, I have encountered an error that I am unsure of how to resolve. When running "npm run build", I receive the following: PS C:\Users\julyj\Desktop& ...

How can you sustain a backend connection using NodeJS as users navigate through different pages?

Currently, I am establishing connections through thrift (node-thrift) with a backend server for api calls. The communication is bidirectional (push/pull) to NodeJS. As users navigate various URLs and Node serves jade templates and javascript files using C ...

Transforming a JSON object into an array with the help of lodash

I am in the process of converting the JSON response into an array to connect it with my Kendo controls. The JSON output I have received is shown below. "Issues": [ { "Id": null, "Key": null, "Values": [ { ...

What is the best way to select an element with a dynamic ID in jQuery?

I'm encountering an issue when passing the ID through a directive. I'm unable to access the element using jQuery within the Link function, even though the element is receiving the correct dynamic ID as a parameter: Here's the Directive: (f ...

Issue found in factory and service dependencies

To retrieve user information, the factory sends a request to the API using ApiRequest.sendRequest: (function() { angular.module('isApp.user', []) .factory('UserProfileFactory', function( $log, ApiRequest, dataUrls ) { // User pr ...

In Swift, search through an array to check if the values of a specific parameter exceed 2000

Is there a way to search within an array for a specific parameter, such as location, and determine if any of the locations have a value of 2000 or higher? I would also like to print the number of locations (rows) that meet this criteria. Thank you! ...

Accessing the 'comment' property within the .then() function is not possible if it is undefined

Why does obj[i] become undefined inside the .then() function? obj = [{'id': 1, 'name': 'john', 'age': '22', 'group': 'grA'}, {'id': 2, 'name': 'mike', &apo ...

Invoking the .html(result) function multiple times within the AJAX success callback

I have implemented this code in my template to handle my ajax request: <script> $(document).ready(function() { $("#send-mail-button").click(function(e){ e.preventDefault(); var nameVar = $('#name&apo ...

Embed a script into an iframe from a separate domain

While experimenting, I attempted to inject a script inside an iframe element using the following method. However, since the child and parent elements do not belong to the same domain (and I am aware that XSS is prevented in modern browsers), I was wonder ...

Converting JavaScript code from Jade into EJS framework

I am currently working on converting code from Jade to EJS and could use some assistance. I have started the translation process, but I'm not entirely confident in my approach. Additionally, I find the syntax used in EJS to be confusing compared to tr ...