Jayaram
Jayaram

Reputation: 6606

Performing delete operations on an immutable JS Map object

I have an immutable JS map with a structure like the below

{
  "a": [
    {"name": "foo", "untracked": true},
    {"name": "bar"}
  ],
  "b": [
    {"name": "baz"},
    {"name": "bar", "untracked": true}
  ]
}

I want to filter this object to only show objects which are tracked - i.e

{
  "a": [
    {"name": "bar"}
  ],
  "b": [
    {"name": "baz"},
  ]
}

Is there a way for me to do this with immutable map operations? i tried the below but it doesnt seem to work

object.map((lis) => lis.filter((li) => li.untracked !== true)).toJS()

object.toList().map((lis) => lis.filter((li) => li.untracked !== true))

Upvotes: 0

Views: 321

Answers (5)

Daya
Daya

Reputation: 119

const data = Immutable.fromJS({
  "a": [
    {"name": "foo", "untracked": true},
    {"name": "bar"}
  ],
  "b": [
    {"name": "baz"},
    {"name": "bar", "untracked": true}
  ]
});

const filteredData = data.map(item => item.filter(iItem => !iItem.get('untracked')));

Upvotes: 0

Mohammed Ashfaq
Mohammed Ashfaq

Reputation: 3426

data = {
  "a": [
    {"name": "foo", "untracked": true},
    {"name": "bar"}
  ],
  "b": [
    {"name": "baz"},
    {"name": "bar", "untracked": true}
  ]
}

let result = Object.entries(data).map(([key, values])=>(
 { key: values.filter(({untracked})=> !untracked) }
))

console.log(result)

Upvotes: 0

Biswadev
Biswadev

Reputation: 1486

let data={
  "a": [
    {"name": "foo", "untracked": true},
    {"name": "bar"}
  ],
  "b": [
    {"name": "baz"},
    {"name": "bar", "untracked": true}
  ]
}
Object.entries(data).map(([key, value]) => {
  data[key]=value.filter(ele=>ele.untracked!=true)
});
console.log("result is : ",data)

Upvotes: 1

brk
brk

Reputation: 50291

Loop through that object and create a new object with keys from old object and then filter the values from the old object where untracked is not equal to false

let obj = {
  "a": [{
      "name": "foo",
      "untracked": true
    },
    {
      "name": "bar"
    }
  ],
  "b": [{
      "name": "baz"
    },
    {
      "name": "bar",
      "untracked": true
    }
  ]
}
let newObj = {};

function filterObject(obj) {
  for (let keys in obj) {
    newObj[keys] = obj[keys].filter(item => {
      return item.untracked !== true
    })
  }
}
filterObject(obj)
console.log(newObj)

Upvotes: 0

Francisco Garcia
Francisco Garcia

Reputation: 376

As per ImmutableJS docs:

filter() returns a new Map with only the entries for which the predicate function returns true.

example:

function someFilterFunction(entry) {
  return !entry.untracked;
}
myMapOfStuff = myMapOfStuff.filter(someFilterFunction);

Link to documentation: https://facebook.github.io/immutable-js/docs/#/Map/filter

EDIT: Remember, the method on an immutable collection returns a COPY of the collection you are operating on. A reassignment must happen if you want to preserve the most up to date reference.

Upvotes: 0

Related Questions