Dushyant Bangal Dushyant Bangal - 2 months ago 7
Node.js Question

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

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.

Answer

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>

Comments