map function for objects (instead of arrays)

前端 未结 30 1964
无人及你
无人及你 2020-11-22 04:23

I have an object:

myObject = { \'a\': 1, \'b\': 2, \'c\': 3 }

I am looking for a native method, similar to Array.prototype.map

30条回答
  •  攒了一身酷
    2020-11-22 04:58

    you can use map method and forEach on arrays but if you want to use it on Object then you can use it with twist like below:

    Using Javascript (ES6)

    var obj = { 'a': 2, 'b': 4, 'c': 6 };   
    Object.entries(obj).map( v => obj[v[0]] *= v[1] );
    console.log(obj); //it will log as {a: 4, b: 16, c: 36}
    
    var obj2 = { 'a': 4, 'b': 8, 'c': 10 };
    Object.entries(obj2).forEach( v => obj2[v[0]] *= v[1] );
    console.log(obj2); //it will log as {a: 16, b: 64, c: 100}
    

    Using jQuery

    var ob = { 'a': 2, 'b': 4, 'c': 6 };
    $.map(ob, function (val, key) {
       ob[key] *= val;
    });
    console.log(ob) //it will log as {a: 4, b: 16, c: 36}
    

    Or you can use other loops also like $.each method as below example:

    $.each(ob,function (key, value) {
      ob[key] *= value;
    });
    console.log(ob) //it will also log as {a: 4, b: 16, c: 36}
    

提交回复
热议问题