lodash Mapping Keys from one object with values in array of objects

偶尔善良 提交于 2019-12-25 17:45:51

问题


I have the following object:

var kmap={
    key1:"useless",
    key2:"useless",
    key3:"useless"
};

I need to map its keys with values of this array of Objects:

var incoming=[
    {value:"asd"},
    {value:"qwe"},
    {value:"zxc"}
];

Result:

{
    key1:"asd",
    key2:"qwe",
    key3:"zxc",
}

Here's how I'm doing it right now:

var result={};

var keys=Object.keys(kmap);

for(var i=0;i<incoming.length;i++)
{
    result[keys[i]]=incoming[i].value;
}

How do I do it using lodash or underscore. Built-in method would be even better, dont want to do for loop.


回答1:


Here's a solution using lodash:

var result = _.zipObject(_.keys(kmap), _.map(incoming, 'value'))

zipObject creates an object given an array of keys and an array of values. The keys we get from kmap and the values are plucked from incoming.

var kmap={
    key1:"useless",
    key2:"useless",
    key3:"useless"
};

var incoming=[
    {value:"asd"},
    {value:"qwe"},
    {value:"zxc"}
];

var result = _.zipObject(_.keys(kmap), _.map(incoming, 'value'))

document.getElementById('result').textContent = JSON.stringify(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

<p>
  <pre id="result"></pre>
</p>



回答2:


You can combine them with the following function:

var kmap={
    key1:"useless",
    key2:"useless",
    key3:"useless"
   
};

var incoming=[
    {value:"asd"},
    {value:"qwe"},
    {value:"zxc"}
];

function combine(obj1, obj2, propToTake) {
  return Object.keys(obj1).map(function(key, i) {
    return {
       [key]: obj2[i] ? obj2[i][propToTake] : undefined
    }
  });
}

console.log(combine(kmap, incoming, 'value'));


来源:https://stackoverflow.com/questions/39774303/lodash-mapping-keys-from-one-object-with-values-in-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!