简体   繁体   中英

Generate object from array list javascript

How would one take a JavaScript array such as:

var listArray = [
  ['a', 'blue', 52],
  ['a', 'green', 27],
  ['a', 'yellow', 36],
  ['b', 'red', 99],
  ['b', 'blue', 11]
];

and merge duplicate in a new objecct. In order to get something like this:

var newObject = {
  'a': {
    'name': 'a',
    'colors': {
      'blue': {
        'name': 'blue',
        'value': 52
      },
      'green': {
        'name': 'green',
        'value': 27
      }
    }
  },
  'b': {
    'name': 'b',
    'colors': {
      'red': {
        'name': 'red',
        'value': 99
      },
      'blue': {
        'name': 'blue',
        'value': 11
      }
    }
  }
}

What I've been try so far but still not working:

var newObject = {};
var colors = {}
for (var item in listArray ) {
    newObject[listArray[item][0]] = {
        'name': myViewData[item][0]
    };
newObject[listArray[item][0]].colors =  colors[listArray[item][1]] = {'name' : listArray[item][1], 'value' : listArray[item][2]};
  }
}

Try this:

var newObject = { };

for (var i = 0; i < listArray.length; i += 1) {
    var triple = listArray[i];

    if (!(triple[0] in newObject)) {
        newObject[triple[0]] = {
            name: triple[0],
            colors: {}
        };
    }

    newObject[triple[0]].colors[triple[1]] = {
        name: triple[1],
        value: triple[2]
    };
}

Use reduce() method

 var listArray = [ ['a', 'blue', 52], ['a', 'green', 27], ['a', 'yellow', 36], ['b', 'red', 99], ['b', 'blue', 11] ]; var res = listArray.reduce(function(a, b) { // check property is defined if (!a[b[0]]) // define the object with name and colors property a[b[0]] = { 'name': b[0], 'colors':{} } // add property in colors sub property a[b[0]]['colors'][b[1]] = { 'name': b[1], 'value': b[2] } // return the updated object return a; }, {}); console.log(res); 


For older browser check polyfill option of reduce method .

Check this snippet please

var listArray = [['a', 'blue', 52], ['a', 'green', 27], ['a', 'yellow', 36], ['b', 'red', 99], ['b', 'blue', 11]];

var newObject = {}

for (var i = 0; i < listArray.length; i++) {
  var item = listArray[i],
             name = item[0],
             color = item[1],
             value = item[2],
             objectItem = newObject[name]

  if (!objectItem) {
    objectItem = {
      name: name,
      colors: {},
    }
  }

  if (!objectItem.colors[color]) {
    objectItem.colors[color] = {
      name: color,
      value: value
    }
  }

  newObject[name] = objectItem
}

console.log(newObject)

I think you might be looking for this (using Array.prototype.forEach() ):

var listArray =[
  ["a", "blue", 52], 
  ["a", "green", 27], 
  ["a", "yellow", 36], 
  ["b", "red", 99], 
  ["b", "blue", 11]
];

var newObject = {};

listArray.forEach(function(el) {
  if(!(el[0] in newObject))
    newObject[el[0]] = {name: el[0], colors: {}}

  if(!(el[1] in newObject[el[0]].colors))
    newObject[el[0]].colors[el[1]] = { name: el[1], value: el[2]}
  else {
    // Do what you want to do if the color is already in there
  }
})

See fiddle

The solution using Object.keys and Array.forEach functions:

var newObject = {};
listArray.forEach(function (v) {
    var k = v[0], color = v[1], innerObj = {'name': color, 'value': v[2]};
    if (!newObject[k]) {
        var obj = {'name': k, 'colors': {}};
        obj['colors'][color] = innerObj;
        newObject[k] = obj;
    } else if (Object.keys(newObject[k]['colors']).indexOf(color) === -1) {
        newObject[k]['colors'][color] = innerObj;
    }
}, newObject);

console.log(JSON.stringify(newObject, 0, 4)); 

The output:

{
    "a": {
        "name": "a",
        "colors": {
            "blue": {
                "name": "blue",
                "value": 52
            },
            "green": {
                "name": "green",
                "value": 27
            },
            "yellow": {
                "name": "yellow",
                "value": 36
            }
        }
    },
    "b": {
        "name": "b",
        "colors": {
            "red": {
                "name": "red",
                "value": 99
            },
            "blue": {
                "name": "blue",
                "value": 11
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM