简体   繁体   中英

Two different array in JavaScript and combine Single array

I have two different array parent and child relational array and combine single array.

this is parent array:- const cat = ['a','b','c']; this is Child array:- const sub =[{name:'cloth',cat:['a','b']},{name:'feshion',cat:['b','a']}]

the output Combine Two array and make single array, I am using map and filter method, It doesn't work the output should be like this const parent =[{name:'a',sub:['cloth','feshion']},{name:'b',sub:['cloth','feshion']},{name:'c',sub:[]}]

Please help me, and Please give me any Idea

const result = cat.map(name => ({name, sub: sub.filter(s => s.cat.includes(name)).map(s => s.name)}));

produces:

[
   { "name": "a", "sub": ["cloth", "feshion"] },
   { "name": "b", "sub": ["cloth", "feshion"] },
   { "name": "c", "sub": [] }
]

Here's an expanded version of that line, easier to follow:

const result = cat.map(catName => {
   const subs = sub
      .filter(s => s.cat.includes(catName))
      .map(s => s.name);

   return {name: catName, sub: subs};
});

Run the code:

 const cat = ['a','b','c']; const sub =[{name:'cloth',cat:['a','b']},{name:'feshion',cat:['b','a']}]; const result = cat.map(name => ({name, sub: sub.filter(s => s.cat.includes(name)).map(s => s.name)})); console.log(result);

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