Convert information from a nested array into an object

I am facing a challenge in converting the following data structure:

 var pets = [
        [
            ['dog', 'Harry'], ['age', 2]
        ],
        [
            ['dog', 'Roger'], ['age', 5]
        ]
    ]

into this desired format:

var dogs = [
    {dog: 'Harry', age: 2},
    {dog: 'Roger', age: 5}
    ]

I have made some attempts but seem to be stuck. Here is my current approach. Any guidance on how to proceed would be highly appreciated. Additionally, any tips on improving the code readability for future reference would be valuable. Thank you.

function arrayToObj(arr) {
  var newArray = [];
  for (var i = 0; i < arr.length; i++) {
    var obj = {};
    for (var j = 0; j < arr[i].length; j++) {
      var key = arr[i][j][0];
      obj[key] = key;
    }
    newArray[i] = obj;
  }
  return newArray; 
}

Answer №1

If you want to manipulate arrays in JavaScript, you can utilize the Array#map and Array#reduce methods.

var pets = [
  [
    ['dog', 'Harry'],
    ['age', 2]
  ],
  [
    ['dog', 'Roger'],
    ['age', 5]
  ]
];


var dogs = pets.map(function(v) {
  return v.reduce(function(obj, arr) {
    obj[arr[0]] = arr[1];
    return obj;
  }, {});
})

console.log(dogs);


Note : To stick with your own code, update the line obj[key] = key; to obj[key] = arr[i][j][1]; or simply use

obj[arr[i][j][0]] = arr[i][j][1];
without the need for the key variable.

var pets = [
  [
    ['dog', 'Harry'],
    ['age', 2]
  ],
  [
    ['dog', 'Roger'],
    ['age', 5]
  ]
];

function arrayToObj(arr) {
  var newArray = [];
  for (var i = 0; i < arr.length; i++) {
    var obj = {};
    for (var j = 0; j < arr[i].length; j++) {
      obj[arr[i][j][0]] = arr[i][j][1];
      // updated here ------^^^^^^^----
    }
    newArray[i] = obj;
  }
  return newArray;
}

var dogs = arrayToObj(pets);

console.log(dogs);

Answer №2

const convertArrayToObject = (arr) => {
  return arr.map((item) => {
     let obj = {};
     item.forEach((data) => {
       obj[data[0]] = data[1];
     })
     return obj
  })
}

Answer №3

Here's an example of how the Map constructor can simplify your code:

var dogs = pets.map(pairs => new Map(pairs))

Answer №4

 let animals = [
    [
        ['cat', 'Fluffy'], ['age', 4]
    ],
    [
        ['dog', 'Max'], ['age', 6]
    ]
]



let animalArr = animals.reduce(function(a, b) {
  let obj = {}
  b.forEach(function(set){
    obj[set[0]] = set[1]
  })
  return a.concat(obj)
}, [])

console.log(animalArr)

Answer №5

Replace obj[key] = arr[i][j][1]; with obj[key] = key

I considered using map and other array methods, but I wanted to illustrate where the mistake was made.

var pets = [
        [
            ['dog', 'Harry'], ['age', 2]
        ],
        [
            ['dog', 'Roger'], ['age', 5]
        ]
    ];
var a=function arrayToObj(arr) {
  var newArray = [];
  for (var i = 0; i < arr.length; i++) {
    var obj = {};
    for (var j = 0; j < arr[i].length; j++) {
      var key = arr[i][j][0];
      obj[key] = arr[i][j][1]; // replace this line with obj[key] = key
    }
    newArray[i] = obj;
  }
  return newArray; 
}
console.log(a(pets));

Answer №6

I believe the following script can be of assistance to you.

function convertArrayToObject(arr) {
        var newObjArray = [];
        for (var i = 0; i < arr.length; i++) {
            var obj = {
                name: '',
                value: ''
            };

            obj.name = arr[i][0][1];
            obj.value = arr[i][1][1];
            newObjArray.push(obj);
        }
        return newObjArray;
    }

Answer №7

To achieve the desired result, you can utilize a simple combination of a nested for() loop within a forEach() loop. TRY IT OUT HERE

var pets = [
  [
    ['cat', 'Whiskers'],
    ['age', 3]
  ],
  [
    ['dog', 'Buddy'],
    ['age', 4]
  ]
];

function convertArrayToObject(arrData) {
  var objData = [];
  arrData.forEach(function(data, index) {
    var tempObj = {};
    for (var i = 0; i < data.length; i++) {
      var arr = data[i];
      tempObj[arr[0]] = arr[1];
    }
    objData.push(tempObj);
  });
  return objData;
}

console.log( convertArrayToObject(pets) );

// RESULT::
        Array[2]
            0: Object
                age: 3
                cat: "Whiskers"
            1: Object
                age: 4
                dog: "Buddy"

</script>

Answer №8

To store the values as properties in an array, reset the array length to zero, convert the array type to a plain object, and then assign it back to the original element.

var pets = [[['dog', 'Harry'], ['age', 2]], [['dog', 'Roger'], ['age', 5]]];

pets.forEach(function (a, i, aa) {
    a.forEach(function (b, _, bb) {
        bb[b[0]] = b[1];
    });
    a.length = 0;
    aa[i] = Object.assign({}, aa[i]);
});

console.log(pets);

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 JavaScript, insert a new date row onto a JSP page

When I click on a hyperlink, I want to add a new row to a jsp page. The functionality is working correctly, but the date function class="dateTxt" is not functioning in the new row. Below are the details of the javascript and jsp function. Javascript: fun ...

What is the best way to search a user-provided text in an array of objects and filter the results?

I am trying to implement a filtering mechanism for objects based on searched text. Currently, I am using the filter method, but it is returning undefined. For instance, if a user enters "Albert Einstein" in the search box, I want to filter quotes related t ...

I am currently seeking a way to validate if a variable corresponds to the choice made in the dropdown menu. Any suggestions on how to accomplish this task?

I have put together a simple drop down menu. My goal is to grab the currently selected value from the drop down list, store it in a variable, and display it in the console. The ultimate objective is to compare that variable with another one to determine if ...

React's setState method may not trigger a re-render

I am currently working on a personal project using React for the front-end and Node for the back-end. One part of the application involves counting the entries when a user submits an image URL, updating it on the server, and then re-rendering it on the fro ...

Clear every other radio button when one is selected

I've customized the radio buttons in Bootstrap, but now I'm having trouble keeping the selected radio button checked. I want the radio buttons to stay checked when clicked and also want them to uncheck all other radio buttons when one is selected ...

Is there a way to retrieve an array generated within a JavaScript loop?

I've been working on retrieving column values from a database and storing them in an array, but I keep getting an empty array as the result. function FetchData(query, db) { var resultArray = new Array(); db.transaction(function(tx) { tx.executeSq ...

My function is not working with jQuery's .append method

As a newcomer to javascript and jquery, I am experimenting with adding html through a javascript function. In an attempt to place the contents of variable "y" at a specific location, I am using a div tag with the id of "Contacts" and trying to append elem ...

A guide to showcasing data within PrimeNG's pie chart component using either JavaScript or Angular

I have utilized the pie chart feature from the PRIMENG CHART PLUGIN My goal is to showcase the values within a pie chart Below, you can find my code for reference **Within app.component.html** <div style="display: block"> <p-chart type="pi ...

Preventing jQuery from triggering bold, underline, and other events

I am stuck with this jsFiddle example: http://jsfiddle.net/RGmNz/6/ My attempts to disable the keyboard shortcuts CTRL + B and CTRL + U have been unsuccessful. $("iframe").contents().find("body").keydown(function(event){ if(event. ...

To what extent can the Vuetify data tables be customized?

https://i.sstatic.net/x4qhA.png I am currently working on replicating the layout shown in the image above. The table is already functional in my Vue project. The following code snippet represents the Vuetify datatable template in use: <v-card> ...

Is there a way to eliminate text from a barcode image using JavaScript or TypeScript?

This is my unique html code <div class="pr-2" style="width: 130px"> <div *ngIf="!element.editing" > <span class="ss">{{element.barcode}}</span> </di ...

Utilizing the arrow function in Object mapping to rearrange objects within an array

In the code snippet below, I am retrieving an object from a Firebase database using snapshot.val() and extracting names using the map function. database.ref('/destinations').once('value', function (snapshot) { const locations = sn ...

What causes the resolution of an array of promises to be slower when each promise is individually resolved in a while loop, as opposed to resolving them all at

I have a model called Posts in my mongoDB database, which contains an array of references to a model called Comments. One of the get requests in my Express application requires me to respond with an array of all Posts in the database, where each Post incl ...

Develop and share a function to be assessed within a different scope's context in JavaScript

Currently, I'm exploring the use of angular and bootstrap tour and I have a challenge in trying to isolate objects within their own area without storing them in the controller. My goal is to store an object in the service, which also contains function ...

Event Stencil Emitter Unclear

I am in the process of developing a web component using stencil and react. The issue I am facing is that even though the value is emitted, it appears as undefined when called within the component. @Event() newModuleClicked: EventEmitter<any>; ...

How can the data controller of a model be accessed within a directive that has been defined with "this"?

I'm struggling with accessing data using a directive, especially when I have defined my models like this: vm = this; vm.myModel = "hello"; Here is an example of my directive: function mySelectedAccount(){ return { restrict: 'A&ap ...

Combine two comma-separated strings in JavaScript to create an array of objects

I have two strings separated by commas that I want to transform into an array of objects. { "id": "1,2,3", "name": "test 1, test 2, test 3" } Is there a way to convert this into the desired object format? { &q ...

What are the different techniques for implementing React-Redux? Comparing Redux-thunk and Redux-Saga

My understanding of Redux is still quite hazy as I delve into various techniques and methods. I am curious to learn about other methods similar to redux-Thunk and redux-saga. Each utilizes distinct functions such as CreateSlice. I am interested to know w ...

Guide to achieving a powerful click similar to a mouse

I've been struggling to get an audio file to play automatically for the past three days, but so far I haven't had any luck. The solutions I've tried didn't work in my browser, even though they worked on CodePen. Can anyone help me make ...

What advantages can be gained by opting for more precise module imports?

As an illustration, consider a scenario where I have an Angular 6 application and need to bring in MatIconModule from the @angular/material library. Two options could be: import { MatIconModule } from '@angular/material/icon'; Or import { Mat ...