1

I have a problem with my code as when I increase the number of elements inside the array it runs only the last added 3 elements only not the full list I don't know what's wrong in my code. please help!

var array = [
  ['make', 'Ford'],
  ['model', 'Mustang'],
  ['year', '1964'],
  ['make', 'Honda'],
  ['model', 'CRV'],
  ['year', '2000']
];

function fromListToObject(array) {
  var obj = Object.create(null); // empty container for my object
  for (var i = 0; i < array.length; i++) { //declare the 1st array loop
    var arr1 = array[i]; //decleare the nested array
    obj[arr1[0]] = arr1[1]; //1st item = 2nd item in the nested array
  }
  return obj;
}

var result = fromListToObject(array);
console.log(result);

6
  • 4
    strong textfunction ?? Commented Jul 13, 2017 at 10:25
  • Why you are using obj[arr1[0]] always?. Isn't it about your loop step increment element i? Commented Jul 13, 2017 at 10:25
  • It's because objects can have only one value for a given property, unless you put value into an array. What result do you expect? Should it be: {make: ["Ford", "Mustang"], model: ["Mustang", "CRV"], year: ["1964", "2000"]} or [{ make: 'Ford', model: 'Mustang', year: '1964' }, { make: 'Honda', model: 'CRV', year: '2000' }]? Commented Jul 13, 2017 at 10:30
  • { make: 'Ford', model: 'Mustang', year: '1964' }, { make: 'Honda', model: 'CRV', year: '2000' } Commented Jul 13, 2017 at 10:32
  • Specify your output format. It is not clear. Commented Jul 13, 2017 at 10:32

4 Answers 4

1

You have to get the data into an array of objects. I'd chunk the original array into pieces of the then keys size, then handle those chunks and create individual objects for them. Note that below will fail if the original array contains chunks that are not equal (keys missing, e.g.), so you will need to add a check for that or be really sure that the original array is always correct:

let array = [
  ['make', 'Ford'],
  ['model', 'Mustang'],
  ['year', '1964'],
  ['make', 'Honda'],
  ['model', 'CRV'],
  ['year', '2000']
];

function toArrOfObj(array) {
  let keys = [...new Map(array).keys()];
  let i, j, res = [], chunk = keys.length;
  for (i = 0, j = array.length; i < j; i += chunk) {
    let tmp = array.slice(i, i + chunk);
    let obj = {};
    for (let [k, v] of tmp) {
      obj[k] = v;
    }
    res.push(obj);
  }
  return res;
}

console.log(toArrOfObj(array));

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

1 Comment

The only answer that works correctly when the input array has for example 5 elements or in general a number of elements not divisible by 3.
1

Does this give you the output you're looking for?

var array = [
  ['make', 'Ford'],
  ['model', 'Mustang'],
  ['year', '1964'],
  ['make', 'Honda'],
  ['model', 'CRV'],
  ['year', '2000']
];

function fromListToObject(data) {
  var cars = [];
  for (var i = 0; i < data.length; i++) {
    var car = {};
    car[data[i][0]] = data[i++][1];
    car[data[i][0]] = data[i++][1];
    car[data[i][0]] = data[i][1];
    cars.push(car);
  }
  return cars;
}

var result = fromListToObject(array);
console.log(result);

Update: Version 2

var array = [
  ['make', 'Ford'],
  ['model', 'Mustang'],
  ['year', '1964'],
  ['make', 'Honda'],
  ['model', 'CRV'],
  ['year', '2000']
];

function fromListToObject(data) {
  var cars = [];

  var car = {};
  data.forEach(function(item) {
    if (item.length < 2)
      return;

    var key = item[0];

    // the car already has the key, so this must be new
    // add the car to the list and create a new one.
    if (car.hasOwnProperty(key)) {
      cars.push(car);
      car = {};
    }

    car[key] = item[1];
  });

  // add the last car in
  cars.push(car);
  return cars;
}

var result = fromListToObject(array);
console.log(result);

3 Comments

Have you tried what happens when the input array has 5 elements?
@LukaszWiktor it was supposed to be basic code with no error handling, but I've added a new version that should handle such scenarios.
Sure, I've already upvoted your first version because it was quite elegant. The second version is even better and works for corner cases.
0

var array = [['make', 'Ford'], ['model', 'Mustang'], ['year', '1964'],['make', 'Honda'], ['model', 'CRV'], ['year', '2000']];


function fromListToObject(array) {  
  var cars = [];
    for(var j = 0; j < array.length/3; j++){ 
      var obj = {};
      for (var i = j; i <= j+3; i++) { 
        var arr1 = array[i];
        obj[arr1[0]] = arr1[1];
      }
      cars.push(obj)
    }
  return cars;
}

var output = fromListToObject(array);
console.log(output);

Comments

0

return full object

{ 
'0': { make: 'Ford', model: 'Mustang', year: '1964' },
'1': { make: 'Honda', model: 'CRV', year: '2000' }
}

var array = [
  ['make', 'Ford'],
  ['model', 'Mustang'],
  ['year', '1964'],
  ['make', 'Honda'],
  ['model', 'CRV'],
  ['year', '2000']
];

function fromListToObject(array) {
  var obj = {};
  var child_obj = {};
  var objindex = 0;
  var index = 0;
  while(array.length) {
    while(array.length && index < 3){
      var arr1 = array.shift();
      child_obj[arr1[0]] = arr1[1];
      index++;
    }
    index = 0;
    obj[objindex]= child_obj;
    child_obj = {};
    objindex++;
  }
  return obj;
}

var result = fromListToObject(array);
console.log(result);

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.