Question

I have 2 arrays with objects in them. I am trying to make a new array based on the information provided in the original 2 arrays. I have jQuery and Underscore available.

The 2 arrays look like the following:

var orgArray = [
  {
    "name": "phone",
    "value": "123-456-7890"
  },
  {
    "name": "color",
    "value": "blue"
  },
  {
    "name": "city",
    "value": "San Diego"
  },
  {
    "name": "zip",
    "value": "54321"
  },
  {
    "name": "email",
    "value": "something@somewhere.com"
  },
  {
    "name": "state",
    "value": "CA"
  },
  {
    "name": "Sale",
    "value": "On Sale"
  }
];

var configArray = [
  {
    "columns": ["phone", "city", "zip"],
    "target": "phone"
  },
  {
    "columns": ["email", "state"],
    "target": "email"
  }
];

If configArray[i].columns contains a string that is in orgArray[i].name then add the target property to the orgArray's object. Here is the new Array that I am trying to create:

var newArray = [
  {
    "name": "phone",
    "value": "123-456-7890",
    "target": "phone"
  },
  {
    "name": "color",
    "value": "blue"
  },
  {
    "name": "city",
    "value": "San Diego",
    "target": "phone"
  },
  {
    "name": "zip",
    "value": "54321",
    "target": "phone"
  },
  {
    "name": "email",
    "value": "something@somewhere.com",
    "target": "email"
 },
  {
    "name": "state",
    "value": "CA",
    "target": "email"
  },
  {
    "name": "Sale",
    "value": "On Sale"
  }
];

Here is my current JS and a fiddle:

jsFiddle: http://jsfiddle.net/9Dv2f/

var newArray = [];

_.each(orgArray, function(element, index, list) { 

  _.each(configArray, function(elem, i) {

    _.each(elem.columns, function (el, x) {

        if (element.name === el.name) {
            console.log(element.name);

            newArray.push({
                name: element.name,
                value: element.value,
                target: elem.target
            });

        }
    });
  });

});

console.log(newArray);
Was it helpful?

Solution

Using $.each() you can do:

$.each(orgArray, function(i, org){
  $.each(configArray, function(j, config){
      if(config.columns.indexOf(org.name) > -1){
          orgArray[i].target = config.target;
      }
  });
});

DOCUMENTATION

OTHER TIPS

You should test if the name exists in elem.column, you can do this by using the .indexOf function. The .indexOf function returns the index of the found object (starting from 0), if it isn't found it will return -1.

if(elem.columns.indexOf(element.name) > -1)

FIDDLE

Something underscore way, not sure(didn't confirmed), should work. Copy the array and map it to updated based on your condition.

var newArray = orgArray;
_.map(newArray, function(elem){
  _.each(configArray, function(elem_config, i) {
    if(_.contains(elem_config, newArray.name)){
      return newArray['target'] = elemconfig.target
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top