jQuery change values of any key of an array of objects

Viewed 3155

I have an array imported via AJAX. I want to create a new array based on the original one and scan through the whole new array in order to clean the value WHATEVER the key associated to it.

The imported dataset looks like this:

[
    {id:"1", color:"red_blue", height:"100_200" },
    {id:"2", color:"green", height:"100_20" },
    {id:"3", color:"orange_yellow", height:"50" }
]

And the jQuery process looks like this

dataSet = JSON.parse(response);

// create a new array based on the imported array
var row = 0;

$.each(dataSet, function(key, value) {
    cleanDataSet.push(dataSet[row]);
    row++;
});

// clean the new array
var row = 0;

// Go through each row of the array
$.each(cleanDataSet, function(key, value) {

    // Go through each key and value of this array
    $.each(cleanDataSet[row], function(key, value) {
        var myVariable = thisValueWhateverTheKey.split('_');

        // if a split is detected in the value
        if (myVariable[1]) {
            // Update the value 
            thisValueWhateverTheKey = myVariable[0];
        }
        row++;
    });
});

console.log(cleanDataSet)

The "thisValueWhateverTheKey" part is obviously the one I can't figure out. It's easy when I target the values of a specific key (I would use "value.nameofmykey" but not that much when I target any value of any key. "value" alone won't work.

4 Answers

You can use value directly, most probably you're geting confused by using key, value in both loops. Also note that you're splitting on double underscore __ which needs to be a single one _ as per your data.

Here's how you can simplify:

$.each(cleanDataSet, function(index, cleanDataSetRow){  

   // Go through each key and value of this array

    $.each(cleanDataSetRow, function(key, value){ 

        var myVariable = value.split('_');

        // if a split is detected in the value

        if(myVariable[1]){

            // Update the value 
            cleanDataSetRow[key] = myVariable[0];

        }

    });
});

I think your code/question is a little confusing - if I understand it properly you are wanting something like this. Note the map function creates a new array populated with the results of calling a provided function on every element in the calling array. e.g.

const data = [{
    id: "1",
    color: "red_blue",
    height: "100_200"
  },
  {
    id: "2",
    color: "green",
    height: "100_20"
  },
  {
    id: "3",
    color: "orange_yellow",
    height: "50"
  }
]

const clean = data.map(x => {
  // x is each object in the original array
  // i.e. data[0], data[1], etc
  for (y in x) {
   // y is each property in the object 
   // e.g. data[0]["id"], data[0]["color"], etc
   // so here we are setting the value of each property of each object
   x[y] = x[y].split('_')[0]
  }

  // finally return each modified object
  return x;
})

// so clean is a new array based on data
// where each property has been set to the correct value
console.log(clean)

If this isn't correct could you possibly edit your question to included and example of how you want the data to look - i.e. before/after.

const data = [
  {
    id: "1",
    color: "red_blue",
    height: "100_200"
  },
  {
    id: "2",
    color: "green",
    height: "100_20"
  },
  {
    id: "3",
    color: "orange_yellow",
    height: "50"
  }
];

var clean = data.map(item => Object.fromEntries(
  Object.keys(item).map(key => [key, item[key].split('_')[0]])
));

console.log(clean);

When you iterate through each object use Object.entries() and destruct each entry (ex. [key, value]):

...
Object.entries(obj).forEach(([key, val]) => {
  if (val === value) {
    obj[key] = ''
  }
... 

let data = [
    {id:"1", color:"red_blue", height:"100_200" },
    {id:"2", color:"green", height:"100_20" },
    {id:"3", color:"orange_yellow", height:"50" }
];

function removeValue(objectArray, value) {
  objectArray.forEach(obj => {
    Object.entries(obj).forEach(([key, val]) => {
      if (val === value) {
        obj[key] = '';
      }
    });
  });
  return objectArray;
}

console.log(removeValue(data, "100_20"));
console.log(removeValue(data, "orange_yellow"));

Related