0

I have a javascript Array with multiple objects.

var array = [{First_name:Mike, Last_Name: Kelly},{First_Name:Charles, Last_Name:Bronson},{First_Name:Chuck, Last_Name:Norris}];

How can i iterate through each object and string.replace('_'g,' ') each key? Essentially i need to replace the underscore with spaces.

2 Answers 2

3
for (var i = 0; i < array.length; i++) {
    for (var prop in array[i]) {
        if (prop.includes("_")) {
            array[i][prop.split("_").join(" ")] = array[i][prop];
            delete array[i][prop];
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

var array = [
  {First_Name: 'Mike', Last_Name: 'Kelly'},
  {First_Name: 'Charles', Last_Name: 'Bronson'},
  {First_Name: 'Chuck', Last_Name: 'Norris'},
];

function convert(obj) {
  const result = {};
  Object.keys(obj).forEach(function (key) {
    result[key.replace(/_/g, ' ')] = obj[key];
  });

  return result;
}


var result = array.map(function (o) {
    return convert(o);
});

console.log(result);

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.