Skip to content

Instantly share code, notes, and snippets.

@florestankorp
Created January 29, 2020 13:53
Show Gist options
  • Save florestankorp/9e3fe76217a5ce8e0f760798050412a3 to your computer and use it in GitHub Desktop.
Save florestankorp/9e3fe76217a5ce8e0f760798050412a3 to your computer and use it in GitHub Desktop.
Mapping an array to object with default keys
const BOOKS = [
'1',
'The Stranger\nThe Outsider',
'Albert Camus',
'1942',
'French',
'2',
'In Search of Lost Time\nRemembrance of Things Past',
'Marcel Proust',
'1913–27',
'French'
];
let currentItem = 0;
const books = [];
const A = BOOKS.forEach((v, i) => {
if (i % 5 == 0) {
books[currentItem] = {};
books[currentItem].id = BOOKS[i];
} else if (i % 5 == 1) {
books[currentItem].title = BOOKS[i];
} else if (i % 5 == 2) {
books[currentItem].author = BOOKS[i];
} else if (i % 5 == 3) {
books[currentItem].year = BOOKS[i];
} else if (i % 5 == 4) {
books[currentItem].lang = BOOKS[i];
currentItem++;
}
});
console.log(books);
// OUTPUT
[
{
id: '1',
title: 'The Stranger\nThe Outsider',
author: 'Albert Camus',
year: '1942',
lang: 'French'
},
{
id: '2',
title: 'In Search of Lost Time\nRemembrance of Things Past',
author: 'Marcel Proust',
year: '1913–27',
lang: 'French'
}
];
@Roms1383
Copy link

Here are the 4 most common ways :

  1. using good ol' for ... loop : for-loop
  2. using Array.forEach :
    forEach
  3. using Array.reduce :
    reduce
  4. using Ramda as a dependency (repo - docs) :
    ramda

Happy coding dude :)

@epatrasc
Copy link

Here another implementation:

// utils
const chunk = (array, size) => {
  const chunked_arr = [];
  let index = 0;
  while (index < array.length) {
    chunked_arr.push(array.slice(index, size + index));
    index += size;
  }
  return chunked_arr;
};

const BOOKS = [
  "1",
  "The Stranger\nThe Outsider",
  "Albert Camus",
  "1942",
  "French",
  "2",
  "In Search of Lost Time\nRemembrance of Things Past",
  "Marcel Proust",
  "1913–27",
  "French"
];
const columnsMapping= ['id', 'title', 'author', 'year', 'lang']

// 1 - split in chunks
const booksChunks = chunk(BOOKS,columnsMapping.length)

// 2 - convert index base columns to named base
// the map loops through all the books
// the reduce maps the index of the book with the index of the columns mapping
const books = booksChunks.map((rawBook) => {
    return rawBook.reduce((accumulator, value, index)=>{
        return {
            ...accumulator,
            [columnsMapping[index]]:value
        }
    },{})
});

console.log(books);

@epatrasc
Copy link

Unreadable mode:

// utils
const chunk = (array, size) => {
  const chunked_arr = [];
  let index = 0;
  while (index < array.length) {
    chunked_arr.push(array.slice(index, size + index));
    index += size;
  }
  return chunked_arr;
};

const BOOKS = [
  "1",
  "The Stranger\nThe Outsider",
  "Albert Camus",
  "1942",
  "French",
  "2",
  "In Search of Lost Time\nRemembrance of Things Past",
  "Marcel Proust",
  "1913–27",
  "French"
];

console.log(chunk(BOOKS,5).map(([id, title, author, year, lang]) => ({ id, title, author, year, lang })));

@epatrasc
Copy link

Here are the 4 most common ways :

  1. using good ol' for ... loop : for-loop
  2. using Array.forEach :
    forEach
  3. using Array.reduce :
    reduce
  4. using Ramda as a dependency (repo - docs) :
    ramda

Happy coding dude :)

Relly cool the idea to spread directly the array to columns name.

@florestankorp
Copy link
Author

Here are the 4 most common ways :

  1. using good ol' for ... loop : for-loop
  2. using Array.forEach :
    forEach
  3. using Array.reduce :
    reduce
  4. using Ramda as a dependency (repo - docs) :
    ramda

Happy coding dude :)

Absolutely brilliant! I love the reduce one. So elegant...

@fidel-karsto
Copy link

Many interesting ways here.
But most of them are too complex in my opinion. Why not use ES6 destructuring?
In combination with a recursive call makes it simple and readable.
What do you think?

 const booksList = [
  '1',
  'The Stranger\nThe Outsider',
  'Albert Camus',
  '1942',
  'French',
  '2',
  'In Search of Lost Time\nRemembrance of Things Past',
  'Marcel Proust',
  '1913–27',
  'French',
  '3',
  'The adventures of Huckleberry Finn',
  'Mark Twain',
  '1885',
  'English'
];

function createBooksFromList(listOfBooks) {
    const [id, title, author, year, language, ...rest] = listOfBooks;
    const result = [];
    result.push({
        id,
        title,
        author,
        year,
        language
    });
    if (rest.length) {
        return result.concat(createBooksFromList(rest));
    }
    return result;       
}

console.log(createBooksFromList(booksList));

@Roms1383
Copy link

Good point too @epatrasc, your chunk method is actually equivalent to ramda's splitEvery 👍


I love the idea of your ...rest parameter and recursive call @fidel-karsto ! 👍 ❤️

The same exact code as a one-liner :

const BOOKS = [
  '1',
  'The Stranger\nThe Outsider',
  'Albert Camus',
  '1942',
  'French',
  '2',
  'In Search of Lost Time\nRemembrance of Things Past',
  'Marcel Proust',
  '1913–27',
  'French',
  '3',
  'The adventures of Huckleberry Finn',
  'Mark Twain',
  '1885',
  'English'
];

const convert = ([ id, title, author, year, language, ...rest ]) => rest.length
? [{ id, title, author, year, language }].concat(convert(rest))
: [{ id, title, author, year, language }]

console.log(convert(BOOKS))

@edmundcwm
Copy link

As mentioned above, this is how I would do it using Array.reduce()

const books = [
  '1',
  'The Stranger\nThe Outsider',
  'Albert Camus',
  '1942',
  'French',
  '2',
  'In Search of Lost Time\nRemembrance of Things Past',
  'Marcel Proust',
  '1913–27',
  'French',
  '3',
  'The adventures of Huckleberry Finn',
  'Mark Twain',
  '1885',
  'English'
]
const newList = books.reduce((acc, cur, index) => {
   if (index % 5 === 0) {
      const [id, title, author, year, language] = books.slice(index, index + 5);
      acc = [...acc, {id, title, author, year, language}];
   }

   return acc;
}, []);

@tutubalin
Copy link

tutubalin commented Jan 30, 2020

class Book {
  constructor(id, title, author, year, lang) {
    this.id = id;
    this.title = title;
    this.author = author;
    this.year = year;
    this.lang = lang;
  }
}

const books = [];

for (let i=0; i<BOOKS.length; i+=5) {
  book = new Book(...BOOKS.slice(i, i+5));
  books.push(book);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment