Home > Net >  How do I create object from multiple arrays?
How do I create object from multiple arrays?

Time:09-02

So let's say I have 2 arrays

keyword = ['test','123']
lang = ['en','fr']

From these two, I want to create an object from keyword that contains each lang. Like below

keywords = [
    {
      keyword: "test",
      lang: "en",
    },
    {
      keyword: "test",
      lang: "fr",
    },
    {
      keyword: "123",
      lang: "en",
    },
    {
      keyword: "123",
      lang: "fr",
    },
  ];

So in total I'll have 4 objects cause each keyword will have their own lang. I've tried mapping but it's just not possible once I have 1 keyword and 2 languages.

CodePudding user response:

use a nested loop:

const keywords = [];
for (const k of keyword) {
  for (l of lang) {
    keywords.push({ keyword: k, lang: l });
  }
}

CodePudding user response:

Use two maps, with the outer one being a flatMap so you don't have nested arrays:

const keyword = ['test', '123']
const lang = ['en', 'fr']

const keywords = keyword.flatMap(key => lang.map(language => ({
  keyword: key,
  lang: language
})))

console.log(keywords)

CodePudding user response:

Oneliner

const keywords = keyword.map(k => lang.map(l => ({ keyword: k, lang: l })));

CodePudding user response:

Here you are, just utilized map() and reduce() to implement what you need.

If you need a further explanation, please let me know.

const keywordArr = ['test','123']
const langArr = ['en','fr']

function makeKeywords(keywords, langs) {
    return keywords.reduce((acc, keyword) => [...acc, ...langs.map(lang => ({keyword, lang}))], []);
};

console.log(makeKeywords(keywordArr, langArr));

  • Related