Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

javascript - 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>";
   }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...