1

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.

  • 1
    _"it's just not possible"_. It is, you can map twice. First map the keywords and then the langs – evolutionxbox Sep 01 '22 at 08:08
  • 1
    Related: [Cartesian product of multiple arrays in JavaScript](https://stackoverflow.com/q/12303989/8746648) – asynts Sep 01 '22 at 09:02
  • I tried to find related question but can't find it. Prolly cause I didn't use the "cartesian" keyword –  Sep 01 '22 at 10:05

4 Answers4

2

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)
evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
1

use a nested loop:

const keywords = [];
for (const k of keyword) {
  for (l of lang) {
    keywords.push({ keyword: k, lang: l });
  }
}
starball
  • 20,030
  • 7
  • 43
  • 238
-1

Oneliner

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

=>

[
   {
      keyword: 'test1',
      lang: 'en'
   },
   {
      keyword": 'test1',
      lang: 'fr'
   },
   {
      keyword": '123',
      lang: 'en'
   },
   {
      keyword": '123',
      lang: 'fr'
   }
]
Mikko Viitala
  • 8,344
  • 4
  • 37
  • 62
  • i was gonna go with this but the returned array is not like what I wanted it retuned arrays of array like `[ [ {...} , {...} ], [{...}, {...} ] ]` –  Sep 01 '22 at 08:51
  • 1
    Hey @Ilmi sorry, didn't notice this comment. Forgot `.flat()` at the end, now it should be fine ;) – Mikko Viitala Sep 02 '22 at 05:04
-1

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));
Mikail Çolak
  • 74
  • 2
  • 3