2

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.

3
  • 1
    @HereticMonkey I got that you referred to the title. My bad :) 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? Commented Apr 7, 2020 at 18:20
  • Sorry for the language barrier. The answer provided by Anurag Srivastava adresses my question completely. 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. Commented Apr 7, 2020 at 18:35

4 Answers 4

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];

        }

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

1 Comment

Thank you very much. I edited the wrong '__'. You are right, I didn't quite understand the implications of the key/value within the loop. I was stuck with the cleanDataSet[row] but I should have used a variable as a reference, as you did. Your answer is perfect and now I get it.
2

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.

3 Comments

Your answer is perfect. Thank you. I used the one provided by Anurag Srivastava simply because it matches the most my initial script (and the rest of my functions) but yours is just as good. However, yours is shorter and I will study it to see the logic behind and probably use it at some point. Thanks !
Ah ok - map is basically a short-hand loop that constructs a new array - you can read about all the array instance methods here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - basically map calls the given function on each element in an array and returns a new array. I'll add comments to my answer to help you...
Thank you very much for the precisions !
1

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

1 Comment

Thank you very much. I haven't tackled the "map" function yet but it seems to be unavoidable when manipulating arrays/objects. Learning arrays and objects isn't so easy (compared to PHP for instance). The documentation is thourough but very hard to understand as a rookie. I try to wrap my head around more intuitive functions right now and when it gets better, I will give those exotic functions a try (exotic to me at least :-) ). I don't know if it's faster but it's definitely shorter. Thanks !
0

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

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.