Reputation: 1848
I have this array object, and I'm trying to create another object out of it. I already have a solution but I think there may be a shorter way of doing what I'm doing. Does anyone know how to make this code shorter or another way using lodash or pure javascript? Thanks a lot in advance!
{
firstName: Mike,
lastName : Brown
}
so far my code works and looks like this:
let response = [
{
"Name": "hobby",
"Value": "poker"
},
{
"Name": "privacy_id",
"Value": "1112"
}, {
"Name": "given_name",
"Value": "Mike"
},
{
"Name": "family_name",
"Value": "Brown"
},
{
"Name": "email",
"Value": "[email protected]"
}
]
const newObj = {};
_.forEach(response, function(obj) {
if(obj.Name === 'given_name') { newObj.firstName = obj.Value}
if(obj.Name === 'family_name'){ newObj.lastName = obj.Value}
});
console.log(newObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Upvotes: 1
Views: 855
Reputation: 1590
This is a good usecase for Array.prototype.reduce since what you want is to transform an array into something - something being an object in your case:
const newObj = response.reduce((acc, curr) => {
acc[curr.Name] = curr.Value;
return acc;
}, {});
This would transform:
const response = [
{
'Name': 'given_name',
'Value': 'Mike'
},
{
'Name': 'family_name',
'Value': 'Brown'
}
]
into:
{
'given_name': 'Mike',
'family_name': 'Brown'
}
Now, if you want to change the naming of the key, you could use some sort of mapping:
const NameMapping = {
given_name: 'firstName',
family_name: 'lastName'
};
const response = [
{
'Name': 'given_name',
'Value': 'Mike'
},
{
'Name': 'family_name',
'Value': 'Brown'
}
]
const newObj = response.reduce((acc, curr) => {
if (NameMapping[curr.Name] === undefined)
return acc;
acc[NameMapping[curr.Name]] = curr.Value;
return acc;
}, {});
So your newObj
would look like this:
{
firstName: 'Mike',
familyName: 'Brown'
}
Upvotes: 1
Reputation: 1768
If you are sure that response
contains both the object with the key given_name
and the object with the key family_name
, you could write this way:
const newObj = {
'given_name': response.filter(el => el.Name ==='given_name')[0].Value,
'family_name': response.filter(el => el.Name ==='family_name')[0].Value,
}
There's the fiddle:
let response = [
{
"Name": "hobby",
"Value": "poker"
},
{
"Name": "privacy_id",
"Value": "1112"
}, {
"Name": "given_name",
"Value": "Mike"
},
{
"Name": "family_name",
"Value": "Brown"
},
{
"Name": "email",
"Value": "[email protected]"
}
]
const newObj = {
'given_name': response.filter(el => el.Name ==='given_name')[0].Value,
'family_name': response.filter(el => el.Name ==='family_name')[0].Value,
}
console.log(newObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Upvotes: 1