Создать массив объектов из объекта, используя javascipt? - PullRequest
0 голосов
/ 19 апреля 2020

Мои исходные данные поступают следующим образом ..

let initial = {
  labels: ['label1', 'label2', 'label3'],
  children: ['child1', 'child2', 'child3'],
  numbers: [1 , 2 , 3]
};

Мне нужен вывод в этом формате.

FINAL_OUTPUT = [
  { labels: 'label1', children: 'child1', numbers: 1 },
  { labels: 'label2', children: 'child2', numbers: 2 },
  { labels: 'label3', children: 'child3', numbers: 3 }
];

Отделил ключи и значения от исходного объекта. Но ударил в создании массива объектов из того же. Пожалуйста, помогите.

Ответы [ 7 ]

1 голос
/ 19 апреля 2020

Вы можете получить записи и отобразить внутренний массив со значениями по указанному индексу.

let initial = { labels: ['label1', 'label2', 'label3'], children: ['child1', 'child2', 'child3'], numbers: [1, 2, 3] },
    result = Object
        .entries(initial)
        .reduce((r, [k, a]) => a.map((v, i) => ({ ...(r[i] || {}), [k]: v })), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
0 голосов
/ 20 апреля 2020

Вы можете использовать loda sh s _.flow(), чтобы создать функцию, которая:

  1. Использует пары для получения массива массивов пар [ключ, [значения]]
  2. Разархивируйте, чтобы получить отдельные ключи от значений
  3. Уничтожьте ключи и значения. Используйте _.unzip() для транспонирования значений, а затем сопоставьте и используйте _.zipObject() с ключами для создания объектов.

const { flow, toPairs, unzip, zipObject } = _;

const fn = flow(
  toPairs, // convert to [key, values] pair
  unzip, // transpose to array of keys, and array of values
  ([keys, values]) => // destructure keys and values
    unzip(values) // transpose the values
      .map(vals => zipObject(keys, vals)) // create object from keys and each set of values
);

const initial = {
  labels: ['label1', 'label2', 'label3'],
  children: ['child1', 'child2', 'child3'],
  numbers: [1, 2, 3]
};

const result = fn(initial);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
0 голосов
/ 20 апреля 2020
let FINAL_OUTPUT =[]

for(let i =0;i<initial.length;i++){
 FINAL_OUTPUT.push(
 {labels: initial.labels[i],
 children: initial.children[i],
 numbers: initial.numbers[i]
 })
}
0 голосов
/ 20 апреля 2020

let initial = {
  labels: ['label1', 'label2', 'label3'],
  children: ['child1', 'child2', 'child3'],
  numbers: [1, 2, 3]
}

/* FINAL_OUTPUT = [
    { labels: 'label1', children: 'child1', numbers: 1 },
    { labels: 'label2', children: 'child2', numbers: 2 },
        { labels: 'label3', children: 'child3', numbers: 3 }
]; */

const result = Object.keys(initial).reduce((acc, x, i, keys) => {
  const arr = keys.map((y, j) => initial[y][i]);
  acc = [...acc, keys.reduce((acc_2, z, k) => ({
    ...acc_2,
    [z]: arr[k]
  }), [])]
  return acc
}, [])

console.log(result)
0 голосов
/ 20 апреля 2020

let initial = {
    labels: ['label1', 'label2', 'label3'],
  children: ['child1', 'child2', 'child3'],
  numbers: [1 , 2 , 3]
};

let keys = Object.keys(initial);
let keyLength = keys[0].length;
let sampleValueArray = initial[keys[0]];
let i = 0;

let result = sampleValueArray.map( (item,index) => {
  let temp = {};
    keys.forEach( key => 
      temp[key] = initial[key][index]
    )
  return temp
})

console.log(result)
0 голосов
/ 19 апреля 2020

Я не знаю ни одной встроенной функции javascript, но вы можете создать для l oop (при условии, что все массивы в объекте имеют одинаковую длину):

for(let i = 0; i < initial[Object.keys(initial)[0]].length; i++){
    FINAL_OUTPUT.push({
        labels: initial.labels[i],
        children: initial.children[i],
        numbers: initial.numbers[i]
    });
}
0 голосов
/ 19 апреля 2020

Это должно делать именно то, что вы хотите, при условии, что все массивы имеют одинаковую длину. Приложив немного творческого подхода, этот алгоритм можно обобщить для подсчета объектов произвольных полей. Вот скрипка .

let initial = {
   labels: [
      'label1', 
      'label2', 
      'label3'
   ],
   children: [
      'child1', 
      'child2', 
      'child3'
   ],
   numbers: [
      1, 
      2, 
      3
   ]
};

function convertObjectToArray(
   labels,
   children,
   numbers
) {
   let final = [];

   for (let i = 0; i < numbers.length; i++) {
      final.push({
         labels: labels[i],
         children: children[i],
         numbers: numbers[i],
      });
  }

  return final;
}

console.log(convertObjectToArray(
   initial.labels,
   initial.children,
   initial.numbers
));
...