Tony Chou
Tony Chou

Reputation: 604

Better way to update value in an object array

In sessionStroage,

key : qq

value : [{"javascript":800},{"python":600},{"html":300}]

I will make some change in it, for examle, just change python to 1000 (I don't know its order in array)

Simulation code

// set storage
sessionStorage.setItem('qq', JSON.stringify([{'javascript': 800}, {'python': 600}, {'html': 300}]));

// get from storage
var ss =  JSON.parse(sessionStorage.getItem('qq'));

This is what I try

// for-loop to update value to 'python'
for (var i in ss) {
    if (Object.keys(ss[i])[0] === 'python'){
        ss[i][Object.keys(ss[i])[0]] = 1000;
    }
}

It works, but it is quite a little bit complicated and not intuitive, is there a better way to do that?

any opinion is ok, thanks inadvanced.

Upvotes: 1

Views: 1442

Answers (3)

Tushar
Tushar

Reputation: 87203

You could use Array#find.

arr.find(obj => obj.hasOwnProperty('python')).python = 1000;

var arr = [{'javascript': 800}, {'python': 600}, {'html': 300}];
arr.find(obj => obj.hasOwnProperty('python')).python = 1000;
console.log(arr);

This will update the value in the arr itself which can then be converted to a string and stored into sessionStorage.

Upvotes: 3

Manikant Gautam
Manikant Gautam

Reputation: 3581

you can achieve so by using simple ForEach method.The forEach() method executes a provided function once for each array element.

var ss = [{'javascript': 800}, {'python': 600}, {'html': 300}]
console.log("Before  "+JSON.stringify(ss))
ss.forEach(function(element) {
if(Object.keys(element) == 'python'){
     element['python'] = 1000;
   }
});
console.log("After "+JSON.stringify(ss))

Upvotes: 3

Dan D
Dan D

Reputation: 2523

If your app permits, you could store the value as an object instead of an Array, then just lookup the item by key:

key: qq value: { "javascript": 800, "python": 600, "html": 300 }

After pulling it out of storage and parsing it would then be:

var ss = JSON.parse(sessionStorage.getItem('qq'));

ss.python = 1000;

Upvotes: 2

Related Questions