重命名属性名称并更改多个对象的值 [英] Rename the property names and change the values of multiple objects
问题描述
在下面的对象中,我想将属性名称 thumb
更改为缩略图
。我还想将 title
的值更改为包含< span>
标签。
以下是我的对象:
$ $ $ $ $ $ $ $ $ $ $ $ $ thumb $ { '/images/01.png',
title:'My title',
},{
thumb:'/images/02.png',
title:'My title',
},{
thumb:'/images/03.png',
title:'My title',
}];
以下是我希望看到的内容:
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> ',
}];
以下是我尝试过的方法:
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>;
:
function changeData(data){
var title;如果(数据[i] .hasOwnProperty(拇指)){
data [i] [数据类型为
(var i = 0; i< data.length; i ++) thumbnail] = data [i] [thumb];
删除数据[i] [thumb];
if(data [i] .hasOwnProperty(title)){//添加缺少的右括号
title = data [i] .title;
data [i] .title ='< span class =red>'+ title +'< / span>';
changeData(data);
编辑:
我尝试使函数具有通用性,但是由于您更新了答案以执行非常具体的操作,因此我已将业务逻辑添加到函数中。
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>";
}
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.
这篇关于重命名属性名称并更改多个对象的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!