Programing

lodash를 사용하여 객체를 배열로 변환

lottogame 2020. 6. 18. 07:52
반응형

lodash를 사용하여 객체를 배열로 변환


lodash로 어떻게 object것을 array바꿀 수 있습니까?

var obj = {
  22: {name:"John", id:22, friends:[5,31,55], works:{books:[], films:[],}
  12: {name:"Ivan", id:12, friends:[2,44,12], works:{books:[], films:[],}
}

// transform to 
var arr = [{name:"John", id:22...},{name:"Ivan", id:12...}]

넌 할 수있어

var arr = _.values(obj);

설명서는 여기를 참조 하십시오.


_.toArray(obj);

다음과 같이 출력됩니다 :

[
  {
    "name": "Ivan",
    "id": 12,
    "friends": [
      2,
      44,
      12
    ],
    "works": {
      "books": [],
      "films": []
    }
  },
  {
    "name": "John",
    "id": 22,
    "friends": [
      5,
      31,
      55
    ],
    "works": {
      "books": [],
      "films": []
    }
  }
]"

누군가 관심이 있다면 현대적인 기본 솔루션 :

const arr = Object.keys(obj).map(key => ({ key, value: obj[key] }));

@KoushikChatterjee 개선에 감사드립니다


나를 위해, 이것은 효과가 있었다 :

_.map(_.toPairs(data), d => _.fromPairs([d]));

돌아서 다

{"a":"b", "c":"d", "e":"f"} 

으로

[{"a":"b"}, {"c":"d"}, {"e":"f"}]

키 (이 경우 ID)를 각 배열 항목의 속성으로 유지하려면 다음을 수행하십시오.

const arr = _(obj) //wrap object so that you can chain lodash methods
            .mapValues((value, id)=>_.merge({}, value, {id})) //attach id to object
            .values() //get the values of the result
            .value() //unwrap array of objects

결과를 얻는 데는 몇 가지 방법이 있습니다. 카테고리로 분류하자 :

ES6 값만 :

이에 대한 주요 방법은 Object.values 입니다. 그러나 Object.keysArray.map사용 하면 예상 결과를 얻을 수 있습니다.

Object.values(obj)
Object.keys(obj).map(k => obj[k])

var obj = {
  A: {
    name: "John"
  },
  B: {
    name: "Ivan"
  }
}

console.log('Object.values:', Object.values(obj))
console.log('Object.keys:', Object.keys(obj).map(k => obj[k]))

ES6 키 및 가치 :

지도와 ES6의 사용 동적 / 계산 된 속성을하고 destructuring 당신이 키를 유지하고지도에서 개체를 반환 할 수 있습니다.

Object.keys(obj).map(k => ({[k]: obj[k]}))
Object.entries(obj).map(([k,v]) => ({[k]:v}))

var obj = {
  A: {
    name: "John"
  },
  B: {
    name: "Ivan"
  }
}

console.log('Object.keys:', Object.keys(obj).map(k => ({
  [k]: obj[k]
})))
console.log('Object.entries:', Object.entries(obj).map(([k, v]) => ({
  [k]: v
})))

Lodash 값만 :

_.values그러나 이를 위해 설계된 방법 은 "바로 가기"와 같은 _.map유틸리티 방법과 객체 의 값만_.toArray 포함하는 배열을 반환하는 유틸리티 방법 이 있습니다 . 그러나 표기법 을 사용하여 객체에서 값을 가져올 수도 있습니다 ._.map_.keysobj[key]

참고 : _.map객체가 전달되면 baseMap기본적으로 forEach객체 속성에있는 핸들러를 사용 합니다.

_.values(obj)
_.map(obj)
_.toArray(obj)
_.map(_.keys(obj), k => obj[k])

var obj = {
  A: {
    name: "John"
  },
  B: {
    name: "Ivan"
  }
}

console.log('values:', _.values(obj))
console.log('map:', _.map(obj))
console.log('toArray:', _.toArray(obj))
console.log('keys:', _.map(_.keys(obj), k => obj[k]))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Lodash 키 및 가치 :

// Outputs an array with [[KEY, VALUE]]
_.entries(obj)
_.toPairs(obj)

// Outputs array with objects containing the keys and values
_.map(_.entries(obj), ([k,v]) => ({[k]:v}))
_.map(_.keys(obj), k => ({[k]: obj[k]}))
_.transform(obj, (r,c,k) => r.push({[k]:c}), [])
_.reduce(obj, (r,c,k) => (r.push({[k]:c}), r), [])

var obj = {
  A: {
    name: "John"
  },
  B: {
    name: "Ivan"
  }
}

// Outputs an array with [KEY, VALUE]
console.log('entries:', _.entries(obj))
console.log('toPairs:', _.toPairs(obj))

// Outputs array with objects containing the keys and values
console.log('entries:', _.map(_.entries(obj), ([k, v]) => ({
  [k]: v
})))
console.log('keys:', _.map(_.keys(obj), k => ({
  [k]: obj[k]
})))
console.log('transform:', _.transform(obj, (r, c, k) => r.push({
  [k]: c
}), []))
console.log('reduce:', _.reduce(obj, (r, c, k) => (r.push({
  [k]: c
}), r), []))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Note that in the above examples ES6 is used (arrow functions and dynamic properties). You can use lodash _.fromPairs and other methods to compose an object if ES6 is an issue.


2017 update: Object.values, lodash values and toArray do it. And to preserve keys map and spread operator play nice:

// import { toArray, map } from 'lodash'
const map = _.map

const input = {
  key: {
    value: 'value'
  }
}

const output = map(input, (value, key) => ({
  key,
  ...value
}))

console.log(output)
// >> [{key: 'key', value: 'value'}])
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>


Transforming object to array with plain JavaScript's(ECMAScript-2016) Object.values:

var obj = {
    22: {name:"John", id:22, friends:[5,31,55], works:{books:[], films:[]}},
    12: {name:"Ivan", id:12, friends:[2,44,12], works:{books:[], films:[]}}
}

var values = Object.values(obj)

console.log(values);

If you also want to keep the keys use Object.entries and Array#map like this:

var obj = {
    22: {name:"John", id:22, friends:[5,31,55], works:{books:[], films:[]}},
    12: {name:"Ivan", id:12, friends:[2,44,12], works:{books:[], films:[]}}
}

var values = Object.entries(obj).map(([k, v]) => ({[k]: v}))

console.log(values);


var arr = _.map(obj)

You can use _.map function (of both lodash and underscore) with object as well, it will internally handle that case, iterate over each value and key with your iteratee, and finally return an array. Infact, you can use it without any iteratee (just _.map(obj)) if you just want a array of values. The good part is that, if you need any transformation in between, you can do it in one go.

Example:

var obj = {
    key1: {id: 1, name: 'A'},
    key2: {id: 2, name: 'B'},
    key3: {id: 3, name: 'C'}
};

var array1 = _.map(obj, v=>v);
console.log('Array 1: ', array1);

/*Actually you don't need the callback v=>v if you
are not transforming anything in between, v=>v is default*/

//SO simply you can use
var array2 = _.map(obj);
console.log('Array 2: ', array2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

However, if you want to transform your object you can do so, even if you need to preserve the key, you can do that ( _.map(obj, (v, k) => {...}) with additional argument in map and then use it how you want.

However there are other Vanilla JS solution to this (as every lodash solution there should pure JS version of it) like:

  • Object.keys and then map them to values
  • Object.values (in ES-2017)
  • Object.entries and then map each key/value pairs (in ES-2017)
  • for...in loop and use each keys for feting values

And a lot more. But since this question is for lodash (and assuming someone already using it) then you don't need to think a lot about version, support of methods and error handling if those are not found.

There are other lodash solutions like _.values (more readable for specific perpose), or getting pairs and then map and so on. but in the case your code need flexibility that you can update it in future as you need to preserve keys or transforming values a bit, then the best solution is to use a single _.map as addresed in this answer. That will bt not that difficult as per readability also.


If you want some custom mapping (like original Array.prototype.map) of Object into an Array, you can just use _.forEach:

let myObject = {
  key1: "value1",
  key2: "value2",
  // ...
};

let myNewArray = [];

_.forEach(myObject, (value, key) => {
  myNewArray.push({
    someNewKey: key,
    someNewValue: value.toUpperCase() // just an example of new value based on original value
  });
});

// myNewArray => [{ someNewKey: key1, someNewValue: 'VALUE1' }, ... ];

See lodash doc of _.forEach https://lodash.com/docs/#forEach

참고URL : https://stackoverflow.com/questions/24674630/transform-object-to-array-with-lodash

반응형