Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename the property names and change the values of multiple objects

In the object below, I'd like to change the property name, thumb, to thumbnail. I'd also like to change the values of the title to include <span> tags.

Here's my object:

var data = [{
    thumb: '/images/01.png',
    title: 'My title',
},{
    thumb: '/images/02.png',
    title: 'My title',
},{
    thumb: '/images/03.png',
    title: 'My title',
}];

here's how I'd like it to look:

var data = [{
    thumbnail: '/images/01.png',
    title: '<span class="red">title 1</span>',
},{
    thumbnail: '/images/02.png',
    title: '<span class="red">title 2</span>',
},{
    thumbnail: '/images/03.png',
    title: '<span class="red">title 3</span>',
}];

Here's what I've tried which doesn't work:

 var i=0, count=data.length;
   for (i=0;i<=count;i++){
    data[i].thumbnail=data[i].thumb;
    data[i].title="<span class='red'>"+data[i].title+"<span>";
   }
like image 778
tim peterson Avatar asked May 30 '12 15:05

tim peterson


2 Answers

This seems to do the trick:

function changeData(data){
    var title;
    for(var i = 0; i < data.length; i++){
        if(data[i].hasOwnProperty("thumb")){
            data[i]["thumbnail"] = data[i]["thumb"];
            delete data[i]["thumb"];
        }

        if(data[i].hasOwnProperty("title")){ //added missing closing parenthesis
            title = data[i].title;
            data[i].title = '<span class="red">' + title + '</span>';
        }
    }
}

changeData(data);

EDIT:

I tried to make the function generic, but since you updated your answer to do very specific things, I've added the business logic to the function.

like image 150
lbstr Avatar answered Nov 15 '22 20:11

lbstr


You can iterate over the array, set a new property in each object, and delete the old property:

data.forEach(function(e) {
   e.thumbnail = e.thumb;
   delete e.thumb;    
});

Here's a working example (check the output in the console).

Obviously you'll want to use a polyfill for Array.prototype.forEach if you want to support older browsers (there's one in the MDN article I linked to above, or you could just use a normal for loop).

like image 39
James Allardice Avatar answered Nov 15 '22 19:11

James Allardice