2

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

以下是胆量:

$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

4 回答 4

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';
于 2012-10-18T03:00:50.510 回答
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;
    }
}
于 2012-10-18T02:57:29.280 回答
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/

于 2012-10-18T03:01:05.947 回答
0

使用现代 JS 可以简单地完成:

var obj = $slides.find(e => e.desc === '127');
if (obj) {
    obj.in = 'yes';
}
于 2019-05-28T08:05:24.083 回答