Creating a JavaScript Object from two arrays

后端 未结 9 831
北海茫月
北海茫月 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 06:50

    Use a loop:

    var result = {};
    for (var i = 0; i < newParamArr.length; i++) {
      result[newParamArr[i]] = paramArr[i];
    }
    
    0 讨论(0)
  • 2020-11-28 06:53

    You can do this using javascript ES 6 new feature :

    For example :

    var keys = ['zahid', 'fahim', 'hasib' ,'iftakhar'];
    
    var ages = [11, 22, 33 ,31];
    
    var testObject = {
        [keys.shift()] : ages.shift(),
        [keys.shift()] : ages.shift(),
        [keys.shift()] : ages.shift(),
        [keys.shift()] : ages.shift()
    
    };
    
    console.log(testObject); // { zahid: 11, fahim: 22, hasib: 33, iftakhar: 31 }
    
    0 讨论(0)
  • 2020-11-28 06:56

    This one works for me.

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

    0 讨论(0)
  • 2020-11-28 07:03

    Using ECMAScript2015:

    const obj = newParamArr.reduce((obj, value, index) => {
        obj[value] = paramArr[index];
        return obj;
    }, {});
    

    (EDIT) Previously misunderstood the OP to want an array:

    const arr = newParamArr.map((value, index) => ({[value]: paramArr[index]}))
    
    0 讨论(0)
  • 2020-11-28 07:03

    You can use Object.assign.apply() to merge an array of {key:value} pairs into the object you want to create:

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

    A runnable snippet:

    var keys = ['foo', 'bar', 'baz'];
    var values = [11, 22, 33]
    
    var result =  Object.assign.apply({}, keys.map( (v, i) => ( {[v]: values[i]} ) ) );
    console.log(result); //returns {"foo": 11, "bar": 22, "baz": 33}

    See the documentation for more

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题