如何將此陣列轉換為該物件?
const arr = [
'key_1', 'text_key_1',
'key_2', 'text_key_2',
'key_3', 'text_key_3',
'key_4', 'text_key_4',
]
const object = {
key_1: 'text_key_1',
key_2: 'text_key_2',
key_3: 'text_key_3',
key_4: 'text_key_4',
}
我正在嘗試減少但沒有成功
uj5u.com熱心網友回復:
這是使用生成器函式和Object.fromEntries的替代方法
const arr = [
'key_1', 'text_key_1',
'key_2', 'text_key_2',
'key_3', 'text_key_3',
'key_4', 'text_key_4',
];
const obj = Object.fromEntries(function * (in_arr) {
const arr = [...in_arr]; // shallow copy
while (arr.length) {
yield arr.splice(0, 2);
}
}(arr));
console.log(obj);
uj5u.com熱心網友回復:
您可以使用reduce和剩余運算子來實作它。基本上,任何偶數休息都是關鍵,任何奇數休息都是價值。
const arr = [
'key_1', 'text_key_1',
'key_2', 'text_key_2',
'key_3', 'text_key_3',
'key_4', 'text_key_4',
]
function arrToObj (arr) {
let lastKey = ''
return arr.reduce((agg, keyOrVal, idx) => {
const isAKey = idx % 2 === 0
if (isAKey) {
lastKey = keyOrVal;
return agg;
}
return {
...agg,
[lastKey]: keyOrVal,
};
}, {});
}
console.log(
arrToObj(arr)
);
uj5u.com熱心網友回復:
只要使用forEach()就可以(假設陣列長度是偶數)
const arr = [
'key_1', 'text_key_1',
'key_2', 'text_key_2',
'key_3', 'text_key_3',
'key_4', 'text_key_4',
]
let result = {}
arr.forEach((e,i) =>{ if(i%2==0){ result[e] = arr[i 1];}})
console.log(result)
uj5u.com熱心網友回復:
Lodash如果你不介意的話:( () , chunk , fromPairs )
const arr = ['key_1', 'text_key_1','key_2', 'text_key_2','key_3', 'text_key_3','key_4', 'text_key_4'];
const obj = _(arr).chunk(2).fromPairs().value();
console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0 }
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520865.html
