7skies
7skies

Reputation: 177

Javascript using Lodash, convert array to plain object, without keys

const arr = [{a:'1',b:'b',c:'c'},{a:'9',b:'b',c:'c'},{a:'3',b:'b',c:'c'}]

const g = _.toPlainObject(arr)
console.log(_.mapValues(g))
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

The Question is how do i get ride, of the index keys0,1,2 in front of each object in the result, and have really plain objects based on a value from each object. Intended result:

{
  "1": {
    "a": "1",
    "b": "b",
    "c": "c"
  },
  "9": {
    "a": "9",
    "b": "b",
    "c": "c"
  },
  "3": {
    "a": "3",
    "b": "b",
    "c": "c"
  }
}

Upvotes: 0

Views: 752

Answers (3)

ray
ray

Reputation: 27265

You can use Array.reduce to remap the object. No library required.

I know this code looks cryptic if you're not familiar with reduce. I promise it's not as complicated as it may appear. Read up on how reduce works and you'll be fine. (And I'm not sure whether my explanatory comments in the code help or just make it even harder to read.)

const arr = [{a:'1',b:'b',c:'c'},{a:'9',b:'b',c:'c'},{a:'3',b:'b',c:'c'}]

const result = arr.reduce(
  // called for each item in arr. merges the current item and returns the result.
  (acc, {a, ...other}) => ( // pull the 'a' value, collect remaining properties in 'other'
    {
      ...acc, // keep prior iterations
      [a]: { a, ...other } // set the value of 'a' as a key, whose value is this iteration's entry
    }),
    {} // start with an empty object
);

console.log(result);

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191986

Use _.mapKeys() to get the keys from the object's values.

Note: since the values are numeric (integer strings), the object properties would be displayed in an ascending order.

const arr = [{a:'1',b:'b',c:'c'},{a:'9',b:'b',c:'c'},{a:'3',b:'b',c:'c'}]

const result = _.mapKeys(_.toPlainObject(arr), o => o.a)

console.log(result)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Upvotes: 0

Rehan Sattar
Rehan Sattar

Reputation: 3945

This is not a valid data structure and is against the rules of objects in javascript. An object or dictionary in python will always be shaped in a key and value pair such as { key: value }

You can get the values of each key using Object.values(). This will return an array of objects containing all the values which you can use. But in general, your data structure is not correct.

Upvotes: -1

Related Questions