2012-05-30 5 views
9

아래 개체에서 thumb의 속성 이름을 thumbnail으로 변경하고 싶습니다. 또한 title의 값을 <span> 태그를 포함하도록 변경하고 싶습니다. 여기속성 이름을 바꾸고 여러 개체의 값을 변경하십시오.

var data = [{ 
    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>"; 
    } 
+0

손으로하지 않으려면 어떻게해야합니까? 그렇다면 귀하의 게시물에 명확히 기재해야합니다. –

+0

@HunterMcMillen이 어떻게 프로그래밍 방식으로 자바 스크립트를 사용하여 수행 될지를 묻습니다. 나는 for 루프가 필요하다고 생각하지만 작동하도록 할 수는 없다. 나는 나의 지위에서 분명히 할 것이다. –

답변

19

이것은 트릭을 수행하는 것 같습니다 :

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); 

편집 :

내가 함수가 일반적인 만들려고하지만 매우 구체적인 일을하고 답변을 업데이트하기 때문에, 내가 함수에 비즈니스 로직을 추가했습니다.

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

가 여기에 working example (콘솔의 출력을 확인) : 당신 수 iterate over the array

+0

forEach 루프를 지적 해 주신 덕분에 원래의 – lbstr

10

은, 기존의 속성을 각 개체에 새로운 속성을 설정하고 delete.

이전 브라우저를 지원하려는 경우 분명히 Array.prototype.forEach에 polyfill을 사용하고 싶습니다 (위에 링크 된 MDN 기사에 하나가 있거나 보통 for 루프를 사용할 수 있음).

+1

을 수정하는 대신 새 개체를 만드는 것이 좋습니다. 우리는 polyfill이 필요하지 않을 때까지 기다릴 수 없습니다. – lbstr

+0

@lbstr이 문제를 우연히 만났고 MVC에서 컨트롤러 자체에서 어떻게 동일한 작업을 수행 할 수 있는지 알고 있습니까? – Vivekh

2

나는 속성 이름의 이름을 바꿀 수있는 좋은 기능을 만들었습니다 https://github.com/meni181818/simpleCloneJS/blob/master/renameProperties.js

예 :

function renameProperties(sourceObj, replaceList, destObj) { 
    destObj = destObj || {}; 
    $.each(sourceObj, function(key) { 
     if(sourceObj.hasOwnProperty(key)) { 
      if(sourceObj[key] instanceof Array) { 
       if(replaceList[key]) { 
        var newName = replaceList[key]; 
        destObj[newName] = []; 
        renameProperties(sourceObj[key], replaceList, destObj[newName]); 
       } else if(!replaceList[key]) { 
        destObj[key] = []; 
        renameProperties(sourceObj[key], replaceList, destObj[key]); 
       } 
      } else if(typeof sourceObj[key] === 'object') { 
       if(replaceList[key]) { 
        var newName = replaceList[key]; 
        destObj[newName] = {}; 
        renameProperties(sourceObj[key], replaceList, destObj[newName]); 
       } else if(!replaceList[key]) { 
        destObj[key] = {}; 
        renameProperties(sourceObj[key], replaceList, destObj[key]); 
       } 
      } else { 
       if(replaceList[key]) { 
        var newName = replaceList[key]; 
        destObj[newName] = sourceObj[key]; 
       } else if(!replaceList[key]) { 
        destObj[key] = sourceObj[key]; 
       } 
      } 
     } 
    }); 
    return destObj; 
} 
:이 함수 내에서 $.each 기능을 사용할 수 있습니다 당신이 jQuery를 사용하고 있기 때문에

var sourceObj = { 
    foo: 'this is foo', 
    bar: {baz: 'this is baz', 
      qux: 'this is qux'} 
}; 
//        the source, rename list 
var replacedObj = renameProperties(sourceObj, {foo: 'foooo', qux: 'quxxxx'}); 
// replacedObj output => { 
     foooo: 'this is foo', 
     bar: {baz: 'this is baz', 
       quxxxx: 'this is qux'} 
    }; 

데모 : http://jsfiddle.net/g2jzse5k/

관련 문제