AkAk47 AkAk47 - 3 months ago 8
JSON Question

Create new Single Object from an ArrayObject

I want an

Object
which I can simply change to JSON format for Exporting later on.
For this I have an
array
of
objects
like this:

[
{
"name": "Test",
"value": "EN Test"
},
{
"name": "Test2",
"value": "DE test2"
}
]


It has to be exact like this

{
"Test" : "EN Test",
"Test2" : "DE test2",
}


So a Single Object with the Value of all Objects of the Array but only the Values of '
name
' and '
value
'.
Angular merge/copy/extend and so on is working with 2 Arrays and just merging them without Options like get only value of name and value.

With
Lodash


object = _.map(objectArray,'name');
Giving me
[ "Test", "Test2", ]
But with multiple
object = _.map(objectArray,['name','value']);
[ false, false, ]
doing
object = _.map(objectarray,_.partial(_.ary(_.pick,2),_,['name','value']));
output is
[ { "name": "Test", "value": "EN Test" }, { "name": "Test2", "value": "DE test2" } ]
not
{ "Test" : "EN Test", "Test2" : "DE test2", }


and so on

object = _.mapValues(objectArray,'name');
{
"0": "Test",
"1": "Values",
}
this.lang = _.mapValues(this.exportData,_.partial(_.ary(_.pick,2),_,['name','value']));

"0": {
"name": "Test",
"value": "Test"
},
"1": {
"name": "TEst2",
"value": "Test2"
},..


What can I do to achieve is

{
"Test" : "EN Test",
"Test2" : "DE test2",
}

Answer

Try this

var a = [
      {
        "name": "Test",
        "value": "EN Test"
      },
      {
        "name": "Test2",
        "value": "DE test2"
      }
    ];

    var obj = {};

    a.forEach(function(node){
        obj[node.name] = node.value
    });

    console.log(obj);

Comments