最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery change values of any key of an array of objects - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Apr 7, 2020 at 18:34 Anurag Srivastava 14.5k4 gold badges37 silver badges46 bronze badges asked Apr 7, 2020 at 18:03 Bachir MessaouriBachir Messaouri 7842 gold badges11 silver badges34 bronze badges 3
  • 1 @HereticMonkey I got that you referred to the title. My bad :) – Anurag Srivastava Commented Apr 7, 2020 at 18:17
  • 1 So basically you want to find a value then remove the key of said value? Or did you want to remove the value only? – zer00ne Commented Apr 7, 2020 at 18:20
  • Sorry for the language barrier. The answer provided by Anurag Srivastava adresses my question pletely. The issue was I should have replace the first "cleanDataSet[row]" of the first loop by a variable so that I can grab it later on. – Bachir Messaouri Commented Apr 7, 2020 at 18:35
Add a ment  | 

4 Answers 4

Reset to default 2

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

发布评论

评论列表(0)

  1. 暂无评论