2012-10-18 41 views
2

我認爲標題解釋得很好。我有一個數組,每個對象有兩個值,我需要通過其中一個值查找對象,然後分配第三個值。javascript按值查找對象並追加附加值

下面是膽:

$slides.push({ 
    img: el.attr('href'), 
    desc: el.attr('title').split('Photo #')[1] 
}); 

它建立一個數組作爲這樣:

Object 
    desc: 127 
    img: img/aaron1.jpg 
Object 
    desc: 128 
    img: img/aaron2.jpg 

我想查找的desc值,然後將分配的in: yes

第三值
$slides.findInArray('desc', '127').addValueToObject('in','yes') 
+1

什麼是名稱中的$?基本上你需要循環和比較。 – epascarello

+1

這是一個全局變量;名字並不重要。循環和比較? – technopeasant

+1

循環...又名for循環。看看數組的每個索引。比較aka x == y,檢查每個對象的屬性值?看起來像一個簡單的解決方案。美元符號沒有任何意義,聽起來像是你試圖讓JavaScript感覺像是另一種語言。 – epascarello

回答

3

http://jsfiddle.net/S3cpa/

var test = [ 
    { 
     desc: 127, 
     img: 'img/aaron1.jpg', 
    }, 
    { 
     desc: 128, 
     img: 'img/aaron2.jpg', 
    } 
]; 

function getObjWhenPropertyEquals(prop, val) 
{ 
    for (var i = 0, l = test.length; i < l; i++) { 
     // check the obj has the property before comparing it 
     if (typeof test[i][prop] === 'undefined') continue; 

     // if the obj property equals our test value, return the obj 
     if (test[i][prop] === val) return test[i]; 
    } 

    // didn't find an object with the property 
    return false; 
} 

// look up the obj and save it 
var obj = getObjWhenPropertyEquals('desc', 127); 

// set the new property if obj was found 
obj.in = obj && 'yes'; 
1

您需要通過for循環運行它

// Loop through the array 
for (var i = 0 ; i < $slides.length ; i++) 
{ 
    // Compare current item to the value you're looking for 
    if ($slides[i]["desc"] == myValue) 
    { 
     //do what you gotta do 
     $slides[i]["desc"] = newValue; 
     break; 
    } 
} 
+0

繼續將跳轉到下一個循環迭代。你需要使用break;語句退出循環。 –

1
easy way 



for (var i = 0; i < $slides.length; i++) 
    { 
     if ($slides[i]["desc"] == "TEST_VALUE") 
     { 
      $slides[i]['in']='yes'; 
     } 
    } 

Another way 

    Array.prototype.findInArray =function(propName,value) 
    { 
     var res={}; 
     if(propName && value) 
     { 
      for (var i=0; i<this.length; i++) 
      { 
      if(this[i][propName]==value) 
      { 
       res = this[i]; 
       break; 
      } 
      } 
     } 
     return res; 
    } 


    Object.prototype.addValueToObject =function(prop,value) 
    { 
     this[prop]=value; 
    } 

---使用它 -

$slides.findInArray('desc', '127').addValueToObject('in','yes'); 

http://jsfiddle.net/s6ThK/

+0

簡單的酒窩。榮譽 – technopeasant

+2

當您找到正確的對象時,您應該從循環中斷開以避免浪費的循環週期。 –

+0

用戶複製我的代碼,包括其中的錯誤,然後得到正確答案? – Jan