andrewplummer / Sugar

A Javascript library for working with native objects.
https://sugarjs.com/
MIT License
4.53k stars 306 forks source link

Finding and changing array's object #601

Closed Costegillio closed 6 years ago

Costegillio commented 7 years ago

Greetings!

I've got array with objects like this: var elsArray = new Sugar.Array( [{a:'1', b:'2'}, {a:'3', b:'4'}, {a:'5', b:'6'}] ); I need to find object with a = 1 and change it's value.

For now i'm using custom function: function findIndexByVal(arr, key, val){ var index = -1; arr.forEach(function(el, i) { var getVal = el[key]; if (getVal == val) { index = i; } }); return index; }

Like this: var getIndex = findIndexByVal(elsArray, "a", "1"); bookArray["raw"][getIndex].a = "test";

Is there easyer way to find and change value?

andrewplummer commented 6 years ago

Sorry this is probably too late to be of use to you, but this isn't the kind of thing there's an easy shortcut for... the simplest way is probably just:

var obj = elsArray.find(obj => obj.a === '1');
if (obj.raw) {
  obj.raw.a = 'test';
}

as a side note if you know the index there is something of a shortcut:

Object.set(elsArray, '0.a', 'test');

I'll close this for now but let me know if you have any questions.

andrewplummer commented 6 years ago

Edit: should be find not findIndex.