JavaScript Array Push key value

前端 未结 2 2018
萌比男神i
萌比男神i 2020-12-03 01:32

Ok, I\'m going a little wrong here and I\'ve already wasted an hour with this so hopefully one of you guys can help me.

var a = [\'left\',\'top\'],
    x = [         


        
2条回答
  •  天命终不由人
    2020-12-03 01:36

    You may use:

    • Array.prototype.map()
    • Array.prototype.reduce()
    • Arrow functions
    • Comma operator

    To create array of objects:

    var source = ['left', 'top'];
    const result = source.map(arrValue => ({[arrValue]: 0}));
    

    Demo:

    var source = ['left', 'top'];
    
    const result = source.map(value => ({[value]: 0}));
    
    console.log(result);


    Or if you wants to create a single object from values of arrays:

    var source = ['left', 'top'];
    const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
    

    Demo:

    var source = ['left', 'top'];
    
    const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
    
    console.log(result);

提交回复
热议问题