0

I have an array of json objects from the server:

var a = [
{id:1,name:"Piano",class:"Instrument"},
{id:2,name:"Guitar",class:"null"},
{id:3,name:"null",class:"null"},.....]

Using underscorejs, is it possible to loop through these objects and change every "null" value in every key with empty string ""?

3
  • 1
    Yes, it is completely possible. It is also possible in plain javascript. Did you try anything? What did you have a problem with? Commented Jan 9, 2015 at 0:07
  • I've tried with underscore but without success. I need tto change every null value in this array with empty string. Commented Jan 9, 2015 at 0:14
  • What was your code and how was it not a success? Commented Jan 9, 2015 at 0:16

2 Answers 2

2

Iterate through the collection and its objects using _.each()* method and replace the values equal to "null" with the empty string. So the logic is the same as you were iterating through two-dimensional array using nested loop.

* I don't suggest to use _.map() here since this method will produce new modified array and I don't know if you need this, though if you want you can also map the array using _.each(obj) inside the mapping function.

var arr,
    searchVal,
    replaceVal;

arr = [
  {id: 1, name: "Piano", class: "Instrument"},
  {id: 2, name: "Guitar", class: "null"},
  {id: 3, name: "null", class: "null"}
];

searchVal = "null";
replaceVal = "";

_.each(arr, function(obj) {
  _.each(obj, function(value, key) {
    if(value === searchVal) {
      obj[key] = replaceVal;
    }
  });
});

console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>

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

Comments

1

Instead of looping through all the data after being parsed from your JSON string, you could just create a custom parser for JSON.parse and save yourself some time.

function customParser(key, value) {
    if (value.name === 'null') {
        value.name = '';
    }
  
    if (value.class === 'null') {
        value.class = '';
    }

    return value;
}

var jsonText = '[{"id":1,"name":"Piano","class":"Instrument"},{"id":2,"name":"Guitar","class":"null"},{"id":3,"name":"null","class":"null"}]',
    a = JSON.parse(jsonText, customParser);

document.body.appendChild(document.createTextNode(JSON.stringify(a)));

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.