user88432
user88432

Reputation: 417

Alternative as Filter

I am mapping if Status has been found. The functionality seem to be working correctly but is there a shorter way or alternative way?

For example:

data = {
  Items: [
    {Id: 434, Status: "Processing"},
    {Id: 223, Status: "Completed"}
  ]
}

mapperData = {
  Id: 223, 
  Name: "Hello World",
  Status: data.Items.filter(function(item) {
      if (item.Id == 223) {
        return item.Status
      }
  })[0].Status,
}

console.log(mapperData)

Returned:

{Id: 223, Name: "Hello World", Status: "Completed"}

Demo: https://jsfiddle.net/jgsr65pv/3/

Upvotes: 0

Views: 709

Answers (2)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can opt to go with a forEach loop on Items array and set your id to compare in a variable:

var data = {
  Items: [
    {Id: 434, Status: "Processing"},
    {Id: 223, Status: "Completed"}
  ]
}

var res = {};
var id = 223;
data.Items.forEach((item)=>{
  res.Id = id;
  res.Name =  "Hello World";
  if (item.Id == id) {
    res.Status = item.Status
  }
});


console.log(res)

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074148

Rather than filter and the [0], use find:

Status: data.Items.find(function(item) { return item.Id == 223; }).Status

E.g.:

mapperData = {
  Id: 223, 
  Name: "Hello World",
  Status: data.Items.find(function(item) { return item.Id == 223; }).Status,
}

Even better with an ES2015+ arrow function:

mapperData = {
  Id: 223, 
  Name: "Hello World",
  Status: data.Items.find(item => item.Id == 223).Status,
}

find was added in ES2015, but can easily be polyfilled for obsolete environments like IE11.

Upvotes: 6

Related Questions