Creating a JavaScript Object from two arrays

后端 未结 9 891
北海茫月
北海茫月 2020-11-28 06:17

I have two arrays: newParamArr[i] and paramVal[i].

Example values in the newParamArr[i] array: [\"Name\", \"Age\", \"Ema

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 07:04

    var keys = ['foo', 'bar', 'baz'];
    var values = [11, 22, 33]
    
    var result = {};
    keys.forEach((key, i) => result[key] = values[i]);
    console.log(result);

    Alternatively, you can use Object.assign

    result = Object.assign(...keys.map((k, i) => ({[k]: values[i]})))
    

    or the object spread syntax (ES2018):

    result = keys.reduce((o, k, i) => ({...o, [k]: values[i]}), {})
    

    or Object.fromEntries (ES2019):

    Object.fromEntries(keys.map((_, i) => [keys[i], values[i]]))
    

    In case you're using lodash, there's _.zipObject exactly for this type of thing.

提交回复
热议问题