Alt-Rock Ninja Cowgirl
Alt-Rock Ninja Cowgirl

Reputation: 161

Transform data from an nested array to an object

I'm trying to turn this:

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

into this:

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

I keep on getting stuck. Here's what I've done so far. Any pointers toward the right direction would be greatly appreciated. Any suggestions on making it more readable would be helpful for me in the future too. Thanks

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; 
}

Upvotes: 1

Views: 143

Answers (8)

fafl
fafl

Reputation: 7385

This is something the Map constructor can do automatically for you:

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

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386634

You could assign the values as properties to the array, set array length to zero and convert the array type to a plain object, and assign it to the same 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);

Upvotes: 0

Poiz
Poiz

Reputation: 7617

You could use a simple for() Loop nested within a forEach() Loop to get the Result you desire. QUICK-TEST HERE

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

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

console.log( arrayToObject(pets) );

    // YIELDS::
        Array[2]
            0: Object
                age: 2
                dog: "Harry"
            1: Object
                age: 5
                dog: "Roger"

</script>

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115222

You can use Array#map and Array#reduce methods.

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


var dogs = pets.map(function(v) { // iterate over the array
  return v.reduce(function(obj, arr) { // iterate over inner array to generate object
    obj[arr[0]] = arr[1]; // define object property based on inner array element
    return obj; // return updated object 
  }, {}); // set initial value as an empty object
})

console.log(dogs);


FYI : If you would like to stick with your own code then you need to update the line obj[key] = key; with obj[key] = arr[i][j][1]; or there is no need of key variable at all simple use single line of code as obj[arr[i][j][0]] = arr[i][j][1];.

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);

Upvotes: 1

Khanjan Bhatt
Khanjan Bhatt

Reputation: 94

I hope following script will help you.

function arrayToObj(arr) {
        var newArray = [];
        for (var i = 0; i < arr.length; i++) {
            var obj = {
                dog: '',
                age: ''
            };

            obj.dog = arr[i][0][1];
            obj.age = arr[i][1][1];
            newArray.push(obj);
        }
        return newArray;
    }

Upvotes: 0

Mahi
Mahi

Reputation: 1727

change obj[key] = arr[i][j][1]; instead of obj[key] = key

i could have done with map and others array method but i want to show where you were wrong .

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]; // change here instead of key 
    }
    newArray[i] = obj;
  }
  return newArray; 
}
console.log(a(pets));

Upvotes: 0

Mike S.
Mike S.

Reputation: 951

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



var petArr = pets.reduce(function(a, b) {
  var obj = {}
  b.forEach(function(set){
    obj[set[0]] = set[1]
  })
  return a.concat(obj)
}, [])

console.log(petArr)

Upvotes: 0

Deepak Jose
Deepak Jose

Reputation: 76

function arrayToObj(arr) {
  return arr.map((item) => {
     var object = {};
     item.forEach((data) => {
       object[data[0]] = data[1];
     })
     return object
  })
}

Upvotes: 1

Related Questions