Transform arrays within arrays to objects

I've been struggling to convert a nested array like the one below:

var array = [
    [['firstName', 'Henry'], ['codeName', 'Etta'], ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a323f3428231a32... },
    [['firstName', 'Bruce'], ['codeName', 'DK'], ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d240c002f2d000c03430e0...}
];

into an object format similar to this:

var newArray = [
    {firstName: 'Henry', codeName: 'Etta', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="422a272c303b022a23...},
    {firstName: 'Bruce', codeName: 'DK', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0f9d1ddf2f0ddd1de9ed3d...}
];

I attempted a solution using the function below, but it didn't yield the desired outcome.

function arrIntoObject(array) {
  var obj = {};

  array.map(function(a) {
    a.map(function(e) {
      obj[e[0]] = e[1];  
    });
  });
  return obj;
}

This seems like a common issue, but despite my efforts, I haven't found a similar question. Any assistance or pointers would be greatly appreciated. Thank you!

Answer №1

To achieve the desired outcome, you can utilize a combination of .map() along with .reduce(), as demonstrated below:

var array = [
    [['firstName', 'Henry'], ['codeName', 'Etta'], ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94fcf1fae6edd4fcf5e6f0f7fbe6f1bafaf1e0">[email protected]</a>'], ['weight', 180], ['occupation', 'repo']],
    [['firstName', 'Bruce'], ['codeName', 'DK'], ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c153d311e1c313d32723f3331">[email protected]</a>'], ['weight', 200], ['occupation', 'enforcement']]
];

var objs = array.map(function (arr) {
  return arr.reduce(function (res, curr) {
    var [key, value] = curr;
    res[key] = value;
    return res;
  }, {});
});

console.log(objs);

Answer №2

One way to simplify the arrays is by converting them into an object structure.

var array = [
  [['firstName', 'Henry'],['codeName', 'Etta'],['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563e3338242f163e3724323539243378383322">[email protected]</a>'],['weight', 180],['occupation', 'repo']],
  [['firstName', 'Bruce'],['codeName', 'DK'],['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9dd4fcf0dfddf0fcf3b3fef2f0">[email protected]</a>'],['weight', 200],['occupation', 'enforcement']]
];

var obj = array.map( arr => arr.reduce( (acc, curr) => { 
    acc[ curr[0] ] = curr[1]; return acc;
}, {}));


console.log(obj)
.as-console-wrapper {top:0; max-height: 100%!important}

Answer №3

You can employ the map() function in conjunction with the spread syntax ... and Object.assign()

var array = [[['firstName', 'Henry'], ['codeName', 'Etta'], ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4cc1cae45">[email protected]</a>'], ['weight', 180], ['occupation', 'repo']],[['firstName', 'Bruce'], ['codeName', 'DK'], ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e476c6362">[email protected]</a>'],['weight', 200], ['occupation', 'enforcement']]];
  
var result = array.map(e => Object.assign({}, ...e.map(([k, v]) => ({[k]: v}))))
console.log(result)

You may also utilize map() followed by reduce() with Object.assign()

var array = [[['firstName', 'Henry'], ['codeName', 'Etta'], ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b13151217">[email protected]</a>'], ['weight', 180], ['occupation', 'repo']],[['firstName', 'Bruce'], ['codeName', 'DK'], ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f9b09bb4949796">[email protected]</a>'],['weight', 200], ['occupation', 'enforcement']]];
  	
var result = array.map(e => e.reduce((r, [k, v]) => Object.assign(r, {[k]: v}),{}))
console.log(result)

Answer №4

If you want to condense an array into a single variable, consider using the reduce method. This method allows you to transform an array into an object with key-value pairs. For more details, refer to MDN

var initialArray = [
    [['firstName', 'Henry'], ['codeName', 'Etta'], ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f098959e8289b098918294939f8295de9e9584">[email protected]</a>'], ['weight', 180], ['occupation', 'repo']],
    [['firstName', 'Bruce'], ['codeName', 'DK'], ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fbb29a96b9bb969a95d5989496">[email protected]</a>'], ['weight', 200], ['occupation', 'enforcement']]
];

function arrayToObject(a) {
  return a.reduce(function (obj, keyValue) {
    obj[keyValue[0]] = keyValue[1];
    return obj;
  }, {});
}

var finalArray = initialArray.map(arrayToObject);

console.log(finalArray);

Answer №5

Perhaps this straightforward logic will be beneficial.

var data = [
  [
    ['name', 'Alice'],
    ['nickname', 'Ally'],
    ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abc3cec5d9d2ebc3cad9cfc8c4d9ce85c5cedf">[email protected]</a>'],
    ['age', 25],
    ['occupation', 'designer']
  ],
  [
    ['name', 'Lara'],
    ['nickname', 'Elle'],
    ['email', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3178505c73715c505f1f525e5c">[email protected]</a>'],
    ['age', 30],
    ['occupation', 'developer']
  ]
];

var result = [];
data.forEach(function(arr1) {
  result.push({});
  arr1.forEach(function(arr2) {
    result[result.length - 1][arr2[0]] = arr2[1];
  })
});

console.log(result);

Answer №6

array.map(arr => arr.reduce((acc, curr) => {
  acc[curr[0]] = curr[1];
  return acc;
}, {}));

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

Unit testing Vue 3 by simulating the push() method of vue-router

As a newcomer to Vue and StackOverflow, I wanted to share my issue. While attempting to run the unit test for my application, I encountered a TypeError. The error message stated: "TypeError: Cannot read properties of undefined (reading 'push')" ...

Angular elements that function as self-validating form controls

I'm wondering if there's a more efficient approach to achieve this, as I believe there should be. Essentially, I have a component that I want to function as an independent form control. This control will always come with specific validation requi ...

What does React default to for the implementation of the ``shouldComponentUpdate`` lifecycle method in its components?

Having a personalized approach to the shouldComponentUpdate() method as part of the React component lifecycle is not obligatory. I am aware that it serves as a boolean function determining whether the render() function will be triggered by changes in comp ...

Changes to the className of a React component will trigger a re-render of

When the className of the parent changes, React children will re-render. import React from 'react'; import { useSelector } from 'react-redux'; import items from './ItemsList.js'; import Item from './Item'; import &ap ...

Exploring the file attributes within nw.js

I'm in the process of developing a native application using nw.js. I have included the following code snippet: <input id="fileDialog" type="file" accept=".pdf,.epub" multiple/><a id="add" href="#">Add</a> Below is my JavaScript cod ...

using angularjs to dynamically apply css styles

Below is the input I have: The HTML code is shown below: <input type="number" ng-class="{negative: amount < 0}" ng-model="amount"/> This is the corresponding CSS code: .negative { color: red; } If the amount is positive, no specif ...

Issue with nested promises not functioning as anticipated within a for loop

I'm currently facing an issue with extending a Promise inside a .then() block. My goal is to update records in the database using a for-loop and then close the database after all updates have been processed. However, the application is exiting abruptl ...

How does Chrome have the capability to access the gist json file? Isn't that typically not allowed?

Fetching a JSON file from Github Gist can sometimes be straightforward, but in certain situations, I have faced difficulties due to CORS restrictions. This has led me to resort to using JSONP instead. Can you shed some light on why this is the case? ...

How can I retrieve the chosen value from an AJAX combobox using JavaScript in an ASP.NET C# application?

How can I retrieve the selected value from an AJAX combobox item using JavaScript in ASP.NET C#? Below is the code snippet: <asp:ComboBox ID="dropdown_dest" runat="server" Width="90%" onfocusout="blurFunction()" AutoCompleteMode="SuggestAppend" CssCla ...

Error: The function cannot be performed on _nextProps.children

I'm having trouble implementing react context with nextJS and I keep encountering this error: Server Error TypeError: _nextProps.children is not a function This is my code for _App.js: import Head from "next/head"; import Router from &q ...

Find the frequency of a specific string within a JSON array

My current task involves working with a stringified array: JSON.stringify(arr) = [{"x":9.308,"y":6.576,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25},{"x":9.42,"y":7.488,"color":"yellow","resti ...

"Encountering a problem with compression in Kafka while using the Node.js client with

I am currently utilizing the kafka-node library to consume data from Kafka. It appears that the data I am receiving is compressed with SNAPPY. How can I decompress this data once it has been retrieved? I attempted to use the node-snappy library for decompr ...

Personalized service implemented in Angular's .config settings

I've come across a few examples of how to insert custom providers into angular's .config, but I'm struggling to do it correctly. Here's the provider I have: (function() { var app = angular.module('application.providers', [& ...

The presence of a .js file is causing a blockage in the loading

As a beginner in the world of jquery/web design, I decided to download a template to experiment and get more familiar with it. Unfortunately, I encountered an issue with a specific script that is causing my jQuery to not load properly. Here is the snippet ...

After saving any HTML, SCSS, or TS file, Angular 12 does not compile immediately

Recently I upgraded my Angular project from version 8 to 12 and then migrated to eslint. However, I have encountered an issue where the compilation does not begin immediately after saving a file. There is a delay of approximately 2 minutes before the compi ...

issue encountered during resource provider setup

Below is my code snippet where I'm attempting to populate a table using ngResource in a RESTful manner. However, when I include configuration directives, I encounter an uncaught object MINERR ASST:22 error. var app = angular.module('infra&apo ...

Adding items from the JSON data to a nested array at index i

In my project, I am working with two files: index.js and list.json. My goal is to extract an element from list.json and insert it into a nested array following the structure [hour][visits per hour]. The hour refers to the index of the hour; for example, ...

An easy way to enable mobility for BootstrapDialog on mobile devices

Currently, I am utilizing the library available at https://github.com/nakupanda/bootstrap3-dialog in order to create a dialog box. However, my issue arises when viewing the dialog on mobile devices where it exceeds the screen size. On desktops, adjusting t ...

"Guide to triggering the display of a particular div based on its class when clicked

I have multiple div elements with the class name dis HTML: <div class="dis">Content</div> <div class="dis">Content</div> <div class="dis">Content</div> and so on ... Additionally, there are various images: <img sr ...

What causes AsyncStorage to lose one value while another value remains intact?

My last session id is stored using AsyncStorage, but for some reason it loses a specific value and I can't figure out why. I created an app that should automatically select the last chosen group on startup. However, after restarting the app, AsyncSto ...