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

How to set and update the value of a TextField in ReactJS using useState and implement an onchange event handler for the input field in TypeScript

Just starting out with ReactJS and MUI development, I have a form with a MuiText field in TypeScript. Seeking assistance on how to use the useState method to update the text field value. Additionally, looking for guidance on adding an onchange function to ...

After changing pages, the checkbox's state is reset to empty

I am currently working with an array of objects structured as follows: const columns = [ { key: "Source_campname", title: "TS Camp Name", customElement: function (row) { return ( <FormControlL ...

Preserving color output while executing commands in NodeJS

My Grunt task involves shelling out via node to run "composer install". var done = this.async(); var exec = require('child_process').exec; var composer = exec( 'php bin/composer.phar install', function(error, stdout, stderr) { ...

Creating intricate mazes using canvas drawing techniques

I recently developed a maze generator as a personal project utilizing a graph. While the generation logic works perfectly, I am facing challenges when it comes to rendering the maze. In my approach, each cell is represented by an array of 4 edges where the ...

Is it possible to create custom input fields using the Stripes Payment-Element?

I recently integrated Stripe into my next.js application to facilitate one-time payments. Following the standard tutorial for Stripe Elements, I created a PaymentIntent on initial render: useEffect(() => { // Create PaymentIntent as soon as the ...

Error when redirecting in Express due to invalid integer input syntax

After executing a PUT query in Postgres through Express, I encountered the following error message: Error: invalid input syntax for integer: "all-calls" This issue seems to be related to the line of code within the router.put function that says response. ...

When using props.onChange(e.target.value) in a textField component in Material UI, it unexpectedly returns an object instead of a value

function FormInput(props) { const classes = formInputStyles(); return ( <div> <TextField onChange={(e) => props.onChange(e.target.value)} InputProps={{ classes, disableUnderline: true }} {...pro ...

How can we trigger the Skill bar effect upon scrolling to the section?

I have created a stunning Skill Bar that is functioning perfectly. However, I am looking to enhance the experience by having the skill bar effect trigger only when I scroll to that specific section. For example, as I navigate from the introduction section ...

Using Q to conduct polling asynchronously with promises

I am facing a situation similar to the one discussed in this blog post: Polling with promises. The author explains using promises for polling until a JobID is returned. I intend to implement this using Q. I want to chain promises together but my attempts ...

Sending the HTML input value to a Knockout view

Can someone assist me with a dilemma I'm facing? Within CRM on Demand, I have a view that needs to extract values from CRM input fields to conduct a search against CRM via web service. If duplicate records are found, the view should display them. Be ...

Is it possible to use JavaScript to append elements with a fade-in effect

I'm looking to add an element with a fade-in animation to another class using JavaScript. Can anyone provide guidance on how to achieve this? Here is what I've tried: success:function(data){ $(".new_posts").append(data); $(".new ...

Display an image using a modal window and Ajax XMLHttpRequest

I was tasked with creating a button that can load various types of content (text, images, videos, etc) into a modal popup window using Ajax without any frameworks. So far, I've been successful with text but have run into issues with loading images. De ...

What is the best way to remove an exported JavaScript file from Node.js?

In my Node.js library package called "OasisLib," there is a file named TypeGenerator.ts. The specific logic within the file is not crucial, but it requires access to files in the filesystem during the project build process. To achieve this, we utilized let ...

Tips for concealing JavaScript and web framework version details from Weppalyzer

To enhance security, we are looking to conceal all JS and Bootstrap information. I have employed the help of the Weppalyzer tool for this purpose. https://i.stack.imgur.com/iLMGF.png Does anyone know how to effectively hide these details? I attempted set ...

The event was triggered, however, some sections of the code did not run

I am currently working on a project called lan-info on GitHub. Here is the code snippet that I am using: let arpSweepCommand = './arpSweep.sh'; app.get('/arp', (req, res) => { console.log('we have a working signal!'); ...

Error: Unable to locate npm package

I am currently working on an Angular application that was created using Grunt and relies on Bower and NPM. Recently, I attempted to install an npm module locally. The installation resulted in the files being stored in the main application directory under ...

Is there a way to securely store my JWT Token within my application's state?

userAction.js -> Frontend, Action export const login = (userID, password) => async (dispatch) => { try { dispatch({ type: USER_LOGIN_REQUEST }); const url = "http://localhost:8080/authenticate/"; const ...

Is there a way to manage the state of a dictionary nested within a list using React JS?

Below is a snippet of my code. I am attempting to update the state of data (which is contained within datasets) to a value defined by the user. constructor(props) { super(props); this.state={ value:'', set:[], coun ...

What is the best way to fetch information from an API using Angular5 with Material2 components?

Here are the 'table.component.html' and 'table.component.ts' files where I am pulling data from an API to display in a table. Below is the object received from the API: [ {position: 1, name: 'Hydrogen', weight: 1.0079, sym ...

What is the key element missing from my code while attempting to integrate Threejs into React?

I recently undertook the task of converting a project from vanilla Three.js to React. For reference, here is the original project: https://codepen.io/Mamboleoo/pen/rNmRqeK And here is the code I have been working on: You can view the code in CodeSandbox ...