0

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.

0

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.