3

I have below object in javascript:

var users = [{
    'user': 'barney',
    'age': 36,
    'active': true
}, {
    'user': 'fred',
    'age': 40,
    'active': false
}, {
    'user': 'pebbles',
    'age': 1,
    'active': true
}];

I want to get a new object from above object but remove active key like below:

var users = [{
        'user': 'barney',
        'age': 36,
    }, {
        'user': 'fred',
        'age': 40,
    }, {
        'user': 'pebbles',
        'age': 1,
    }];

I know that I can create the object by a for-loop, but I am looking for a better way to do that. Whether it can be done by one line of lodash code?

2

4 Answers 4

5

If you can use the latest JavaScript features...

users = users.map(({ active, ...rest }) => rest);

https://jsfiddle.net/22kqjvc5/1/

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

1 Comment

1+ - Nice! That is a really clever usage of the spread operator.
4

An ES6 way to do this

var users = [{
    'user': 'barney',
    'age': 36,
    'active': true
  }, {
    'user': 'pebbles',
    'age': 1,
    'active': true
}];

console.log ( _.map(users, i => _.pick(i, 'user', 'active'))  )
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.core.js"></script>

Inspired by this

Comments

3

You don't need a library.

var result = users.map(el => {
   delete el.active;
   return el;
});

Comments

3

You could use _.map in combination with _.omit in order to omit the active property:

Example Here

_.map(users, user => _.omit(user, 'active'))

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.