[英]transform object to array with 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...}]
如果有人感興趣,可以使用現代本地解決方案:
const arr = Object.keys(obj).map(key => ({ key, value: obj[key] }));
或(不是 IE):
const arr = Object.entries(obj).map(([key, value]) => ({ key, value }));
_.toArray(obj);
輸出為:
[
{
"name": "Ivan",
"id": 12,
"friends": [
2,
44,
12
],
"works": {
"books": [],
"films": []
}
},
{
"name": "John",
"id": 22,
"friends": [
5,
31,
55
],
"works": {
"books": [],
"films": []
}
}
]"
對我來說,這有效:
_.map(_.toPairs(data), d => _.fromPairs([d]));
事實證明
{"a":"b", "c":"d", "e":"f"}
進入
[{"a":"b"}, {"c":"d"}, {"e":"f"}]
有很多方法可以得到你想要的結果。 讓我們把它們分成幾類:
僅 ES6 值:
主要方法是Object.values 。 但是使用Object.keys和Array.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 動態/計算屬性和解構,您可以保留鍵並從地圖返回一個對象。
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
_.keys
並使用obj[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>
請注意,在上面的示例中使用了 ES6(箭頭函數和動態屬性)。 如果 ES6 有問題,您可以使用 lodash _.fromPairs
和其他方法來組合對象。
如果您希望將鍵(在這種情況下為 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
2017 年更新: Object.values 、 lodash values和toArray做到了。 並保留鍵映射和擴展運算符玩得很好:
// 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>
使用純 JavaScript ( 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);
如果您還想保留鍵使用Object.entries
和Array#map
像這樣:
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);
在所有答案中,我認為這個是最好的:
let arr = Object.entries(obj).map(([key, val]) => ({ key, ...val }))
轉換:
{
a: { p: 1, q: 2},
b: { p: 3, q: 4}
}
到:
[
{ key: 'a', p: 1, q: 2 },
{ key: 'b', p: 3, q: 4 }
]
變回:
let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { ...val }; return obj; }, {})
要轉換回保留值中的鍵:
let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { key, ...val }; return obj; }, {})
會給:
{
a: { key: 'a', p: 1, q: 2 },
b: { key: 'b', p: 3, q: 4 }
}
對於最后一個示例,您還可以使用 lodash _.keyBy(arr, 'key')
或_.keyBy(arr, i => i.key)
。
var arr = _.map(obj)
您也可以將_.map
函數( lodash
和underscore
)與object
一起使用,它會在內部處理這種情況,用您的 iteratee 迭代每個值和鍵,最后返回一個數組。 事實上,如果你只想要一個值數組,你可以在沒有任何迭代的情況下使用它(只是_.map(obj)
)。 好的部分是,如果您需要在兩者之間進行任何轉換,您可以一次性完成。
例子:
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>
但是,如果你想轉換你的對象,你可以這樣做,即使你需要保留密鑰,你也可以這樣做( _.map(obj, (v, k) => {...}
)和額外的參數在map
,然后以您想要的方式使用它。
但是,還有其他 Vanilla JS 解決方案(因為每個lodash
解決方案都應該是它的純 JS 版本),例如:
Object.keys
然后map
它們map
到值Object.values
(在 ES-2017 中)Object.entries
然后map
每個鍵/值對(在 ES-2017 中)for...in
循環並使用每個鍵來獲取值還有很多。 但是由於這個問題是針對lodash
(並假設有人已經在使用它),那么您無需lodash
考慮版本、方法支持和錯誤處理(如果沒有找到的話)。
還有其他 lodash 解決方案,如_.values
(對於特定的 perpose 更具可讀性),或者獲取對然后映射等等。 但是如果您的代碼需要靈活性,您可以在將來更新它,因為您需要保留keys
或稍微轉換值,那么最好的解決方案是使用本答案中提到的單個_.map
。 根據可讀性,這也不會那么困難。
如果您想將對象的一些自定義映射(如原始 Array.prototype.map)映射到數組中,您可以使用_.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' }, ... ];
請參閱 _.forEach https://lodash.com/docs/#forEach 的lodash
文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.