qg_java_17137
qg_java_17137

Reputation: 3569

Is there a better way to replace my double forEach method?

I have two list, as bellow:

var a = ["a", "b"]

var b = [{name:"a1", belong_type:"a" }, {name:"a2", belong_type:"a" }, {name:"b1", belong_type:"b" },]

I want to put them like this:

var data = {}


a.forEach(a_item => {
  data[a_item] = []
  b.forEach(b_item => {
    if (a_item === b_item.belong_type){
      data[a_item].push(b_item)
    }
  })
})

console.log(data)

the result is :

{ a: 
   [ { name: 'a1', belong_task_type: 'a' },
     { name: 'a2', belong_task_type: 'a' } ],
  b: [ { name: 'b1', belong_task_type: 'b' } ] }

I think my method use two forEach, I don't know whether there is a better way to realize the result, who can tell me if there is a better way?

Upvotes: 1

Views: 41

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122037

You could use reduce method on a array and inside use filter method on b array to return objects where belong_type is equal to current element in reduce.

var a = ["a", "b"]
var b = [{name:"a1", belong_type:"a" }, {name:"a2", belong_type:"a" }, {name:"b1", belong_type:"b" }]

const result = a.reduce((r, e) => {
  r[e] = b.filter(({belong_type}) => belong_type == e)
  return r;
}, {})

console.log(result)

You could also use Object.assign method inside reduce to write it as a one-liner.

var a = ["a", "b"]
var b = [{name:"a1", belong_type:"a" }, {name:"a2", belong_type:"a" }, {name:"b1", belong_type:"b" }]

const result = a.reduce((r, e) => Object.assign(r, {[e]: b.filter(({belong_type}) => belong_type == e)}), {})
console.log(result)

Upvotes: 2

Related Questions