1

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

8 Answers 8

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

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

Comments

0

 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)

Comments

0

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

Comments

0

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

Comments

0

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>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.