1

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",
}

2 Answers 2

2

Use native JavaScript Array#reduce method.

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

// iterate over array
var res = data.reduce(function(obj, v) {
  // define the object property
  obj[v.name] = v.value;
  // return the object
  return obj;
  // define initial value as empty object
  // for storing the result
}, {})

console.log(res);

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

Comments

0

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

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.