1

I have a normalized Object like this (for example):

const raw = {
  1: { foo: 1, bar: 1, flag: 0 },
  4: { foo: 4, bar: 4, flag: 1 },
  11: { foo: 11, bar: 11, flag: 0 },
  ...
}

I wanna delete values which have flag: 1.

{
  1: { foo: 1, bar: 1, flag: 0 },
  11: { foo: 11, bar: 11, flag: 0 },
  ...
}

How can I do this immutably?

4
  • Any particular reason you're not using an Array, Set, or Map for this? Commented Sep 1, 2018 at 6:43
  • @Taichi is it an Array of objects? as you have mentioned in your comment? Commented Sep 1, 2018 at 6:47
  • @Brad I have my data in this format, cuz I can get datum easily like raw[1] . Please see github.com/paularmstrong/normalizr Commented Sep 1, 2018 at 6:47
  • @amrendersingh no, it is Object. I wanna convert raw like in the question Commented Sep 1, 2018 at 6:48

3 Answers 3

6

You can use Object.values() and Array.prototype.filter()

var obj = {
  1: { foo: 1, bar: 1, flag: 0 },
  2: { foo: 2, bar: 2, flag: 1 },
  3: { foo: 3, bar: 3, flag: 0 }
}
var newobj = Object.assign({}, Object.values(obj).filter(o => o.flag != 1));
console.log(newobj);

You can use reduce() to keep the keys:

var obj = {
  1: { foo: 1, bar: 1, flag: 0 },
  2: { foo: 2, bar: 2, flag: 1 },
  3: { foo: 3, bar: 3, flag: 0 }
}
var newobj = Object.keys(obj).reduce((a,c) => {
  if(obj[c].flag != 1) 
   a[c] = obj[c]; return a;
},{});
console.log(newobj);

Sign up to request clarification or add additional context in comments.

1 Comment

I think this deletes keys of raw, doesn't it?
2

You can object filtering by lodashjs. https://lodash.com/docs/#filter

_.filter(obj, o => !o.flag);

Comments

1

You can use Object.keys() and .reduce() methods:

let data = {
  1: { foo: 1, bar: 1, flag: 0 },
  2: { foo: 2, bar: 2, flag: 1 },
  3: { foo: 3, bar: 3, flag: 0 }
};

let result = Object.keys(data).reduce((a, c) => {
  if(data[c].flag !== 1)
    a[c] = Object.assign({}, data[c]);
  
  return a;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.