0

I have an array of objects that i need to convert to a single object. ex:need to convert

var data=[
  {
    "name": "EMPRESA",
    "value": "CMIP"
  },
  {
    "name": "DSP_DIRECAO",
    "value": "CMIP@040@1900-01-01"
  },
  {
    "name": "DSP_DEPT",
    "value": "CMIP@040@1900-01-01@42@1900-01-01"
  },

... ]

to

   {
    "EMPRESA": "CLCA",
    "DSP_DIRECAO": "CLCA@100@1900-01-01",
    "DSP_DEPT": "CLCA@100@1900-01-01@100@1900-01-01",
    ...
  }

Turn data[x][name] to propertie and data[x][value] to atribute value Thanks

1
  • 2
    Please edit the question and add the code you've tried. The can simply be done by looping over array elements and adding key-value pairs to the object. Commented Sep 16, 2016 at 15:39

3 Answers 3

9

Doesn't use LoDash, but a straight forward reduce()

var obj = data.reduce( (a,b) => {
    return a[b.name] = b.value, a;
}, {});

var data=[
  {
    "name": "EMPRESA",
    "value": "CMIP"
  },
  {
    "name": "DSP_DIRECAO",
    "value": "CMIP@040@1900-01-01"
  },
  {
    "name": "DSP_DEPT",
    "value": "CMIP@040@1900-01-01@42@1900-01-01"
  }
]

var obj = data.reduce( (a,b) => {
    return a[b.name] = b.value, a;
}, {});

console.log(obj);

Doing the same in LoDash would be something like

var obj = _.transform(data, (a,b) => {
    return a[b.name] = b.value, a;
},{});
Sign up to request clarification or add additional context in comments.

3 Comments

Hadn't thought of that. Kudos!
Nice use of comma operator
The transform method doesn't need to return the accumulator like reduce does. You can do something like: const output = _.transform(data, (a, b) => a[b.name] = b.value, {});
2

On lodash 4.15,

_.chain(data).keyBy("name").mapValues("value").value()

On lodash 3.10,

_.chain(data).indexBy("name").mapValues("value").value()

1 Comment

im using lodash 3.10 ... QuadTable.js:352 Uncaught TypeError: _.chain(...).keyBy is not a function
0
var newObj = {}
var data = [{
    "name": "EMPRESA",
    "value": "CMIP"
}, {
    "name": "DSP_DIRECAO",
    "value": "CMIP@040@1900-01-01"
}, {
    "name": "DSP_DEPT",
    "value": "CMIP@040@1900-01-01@42@1900-01-01"
}]
data.forEach(function(d) {
    newObj[d.name] = d.value
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.