javascript按值在数组中查找对象并附加其他值

时间:2012-10-18 02:49:14

标签: javascript arrays object find push

我认为标题解释得很好。我有一个数组,每个对象有两个值,我需要通过其中一个值查找对象,然后为它分配第三个。

以下是胆量:

$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')

4 个答案:

答案 0 :(得分: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 :(得分: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;
    }
}

答案 2 :(得分: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/

答案 3 :(得分:0)

使用现代JS可以轻松完成:

var obj = $slides.find(e => e.desc === '127');
if (obj) {
    obj.in = 'yes';
}