-1

This is my object:

{
    "user": {
        "id": 11,
        "name": null,
        "email": null,
        "phone": "000000000",
        "age": null,
        "role": "user",
        "otp": "656440",
        "otpCreatedAt": null,
        "createdAt": "2020-10-24T07:38:54.000Z",
        "updatedAt": "2020-10-24T07:38:54.000Z"
    }
}

Am getting this from querying on mysql db, now i dont want to send all the values to response ! Instead i need selected values to be sent under a single key !

Expected output

{
    "user" :{
        "name": null,
        "email": null,
        "phone": "000000000",
        "age": null,
      }
}

I can split this and send like name: user.name etc but i need all the needed under single key !

How to achieve this ?

As of now am just splitting it like this !

phone: user.phone, name: user.name, age: user.age, email: user.email
nothingimp
  • 79
  • 7
  • `const {name, email, phone, age} = input.user, output = {user: {name, email, phone, age}};` – Jaromanda X Oct 24 '20 at 07:58
  • 1
    Duplicate of [Filter object properties by key in ES6](https://stackoverflow.com/questions/38750705/filter-object-properties-by-key-in-es6) – Guy Incognito Oct 24 '20 at 08:01

3 Answers3

0

Would it be a good solution? I would like to take this way.

const { user: { name, email, phone, age } } = {
    "user": {
        "id": 11,
        "name": null,
        "email": null,
        "phone": "000000000",
        "age": null,
        "role": "user",
        "otp": "656440",
        "otpCreatedAt": null,
        "createdAt": "2020-10-24T07:38:54.000Z",
        "updatedAt": "2020-10-24T07:38:54.000Z"
    }
};

const expectedResult = {
  "user": { name, email, phone, age }
}
Everest Climber
  • 1,203
  • 1
  • 9
  • 15
0

Simply construct a new object with the keys/values you need from the old object.

let u = {
    "user": {
        "id": 11,
        "name": null,
        "email": null,
        "phone": "000000000",
        "age": null,
        "role": "user",
        "otp": "656440",
        "otpCreatedAt": null,
        "createdAt": "2020-10-24T07:38:54.000Z",
        "updatedAt": "2020-10-24T07:38:54.000Z"
    }
}

let newuser = {user: {name: u.user.name, email: u.user.email, phone: u.user.phone, age: u.user.age}};
console.log(newuser);
ATD
  • 1,344
  • 1
  • 4
  • 8
0

Properties can be excluded with the JSON.parse reviver and the JSON.stringify replacer :

var o = { "user": { "id": 11, "name": null, "email": null, "phone": "000000000", "age": null, "role": "user", "otp": "656440", "otpCreatedAt": null, "createdAt": "2020-10-24T07:38:54.000Z", "updatedAt": "2020-10-24T07:38:54.000Z" } }

var j = JSON.stringify(o, (k, v) => /^(|user|name|email|phone|age)$/.test(k) ? v : undefined, 2)

console.log(j)
Slai
  • 22,144
  • 5
  • 45
  • 53