Denys Rybkin
Denys Rybkin

Reputation: 787

How to remove unwanted properties from linked object?

I have the following structure:

{
  cp: {
    id: 8,
    login: "[email protected]",
    name: "Yuri",
    age: 19,
    ...
  },
  admin: {
    id: 19,
    login: "test",
    password: "somehash",
    ...
  }
}

I wish this object to have id and login properties only, like:

{
  cp: {
    id: 8,
    login: "[email protected]"
  },
  admin: {
    id: 19,
    login: "test"
  }
}

Is there way to do this using lodash ? I have read this answer but I don't know how to do the same operations with my structure. Please, help.

Upvotes: 0

Views: 86

Answers (3)

axtck
axtck

Reputation: 3965

I know you specifically searched for a solution using lodash, but you could also accomplish the same like this.

const data = {
  cp: {
    id: 8,
    login: "[email protected]",
    name: "Yuri",
    age: 19,
  },
  admin: {
    id: 19,
    login: "test",
    password: "somehash",
  }
}

const result = Object.fromEntries(Object.entries(data)
  .map(([k, {id, login}]) => [k, {id, login}]));

console.log(result);

It maps through the objects entries and returns only the properties you need as new entries to recreate the object from.

Upvotes: 1

tuan nguyen
tuan nguyen

Reputation: 386

i do not test this, code, but hope it help you

var obj = {
  cp: {
    id: 8,
    login: "[email protected]",
    name: "Yuri",
    age: 19,
    ...
  },
  admin: {
    id: 19,
    login: "test",
    password: "somehash",
    ...
  }
}
var model = {
   id:null,
   login:null
};
Object.keys(obj).forEach(e=>obj[e] = _.pick(obj[e], _.keys(model)))

update without lodash

var obj = {
                cp: {
                    id: 8,
                    login: "[email protected]",
                    name: "Yuri",
                    age: 19,
                },
                admin: {
                    id: 19,
                    login: "test",
                    password: "somehash",
                }
            }
            const keeps = ["id","login"];
            Object.keys(obj).forEach(e=>{
                Object.keys(obj[e]).forEach(f=>{
                    if(!keeps.includes(f)){
                        delete obj[e][f]
                    }
                })
            })

Upvotes: -1

Hassan Imam
Hassan Imam

Reputation: 22534

You can use transform and pick to convert your object.

const obj = { cp: { id: 8, login: "[email protected]", name: "Yuri", age: 19, }, admin: { id: 19, login: "test", password: "somehash", }, },
      result = _.transform(obj, (r, v, k) => {
        r[k] = _.pick(v, ['id', 'login']);
        return r;
      }, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

Upvotes: 1

Related Questions