简体   繁体   中英

How do I create object from multiple arrays?

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.

use a nested loop:

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

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)

Oneliner

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM