Home > OS >  How to convert an Array to an Object.?
How to convert an Array to an Object.?

Time:10-21

How can I convert this array to this object?

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',
}

I'm trying with Reduce but without success

CodePudding user response:

Here's an alternative using a generator function and 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);

CodePudding user response:

You can achieve it with a reduce and remainder operator. Basically any even rest is a key and any odd rest is a value.

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)
);

CodePudding user response:

Just using forEach() can do it(suppose the array length is even)

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)

CodePudding user response:

Lodash if you don't mind: ((), 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>

  • Related