0

Do you have an optimised solution for the following.

let say,

x = { users: [ {id: 1}, {id:2}, {id:3} ] }

I want to make a new key with same values, the output should be,

{ users: { list: [ {id: 1}, {id:2}, {id:3} ], count: 3 }

Using only JS or Underscore with one line code w/o any extra effort.

I know other tricks to do the same, but do we have one line solution for the same ?
Help appreciated...
Thanks.

1
  • 1
    your output is invalid. should count be a property of users, or of the enclosing (unnamed) object? Commented Apr 12, 2018 at 4:55

3 Answers 3

3

Create the object, and assign the x array to list. However, count should be a getter, since the list length might change:

const x = { users: [{ id: 1 }, { id: 2 }, { id: 3 }] };
const result = {
  users: {
    list: x.users,
    get count() { return this.list.length; }
  }
};

console.log(JSON.stringify(result));

result.users.list.push({ id: 4 });

console.log(JSON.stringify(result));

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

Comments

2

I'm not sure why this is to be an optimised solution because this is a simple plain-JavaScript problem:

let x = { users: [{ id: 1 }, { id: 2 }, { id: 3 }] };
let result = {
  users: {
    list: x.users,
    count: x.users.length
  }
};

console.log(result);

3 Comments

Ok, I just find my mistake here, actually I'm trying obj.user.list = { obj.users }, so I'm having array with new object too..
huh @BHARGAV - this gives you exactly what you want in the question
@BHARGAV -- I didn't get you quite right here. Could you elaborate? Or my answer is your desired solution?
2

Sure, just define the property as an object

const obj = {
  users: [{
    id: 1
  }, {
    id: 2
  }, {
    id: 3
  }]
};
obj.users = { list: obj.users, count: obj.users.length };
console.log(obj);

I recommend focusing on code clarity rather than on line conservation though

2 Comments

Ok, I just find my mistake here, actually I'm trying obj.user.list = { obj.users }, so I'm having array with new object too..
Can you edit your question to make it clear what you're actually trying to find?

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.