Home > Enterprise >  How to get particular data values from JSON Node.js?
How to get particular data values from JSON Node.js?

Time:10-10

This is my JSON file output

let employees = [{
          "id":1,
          "name":"Lann",
          "username":"brot",
          "email":"[email protected]",
          "address":{
             "city":"Gweh",
             "zipcode":"92998-3874",
             "geo":{
                "lat":"45",
                "lng":"77"
             }
          }}]

How I get id, name and email from that like below.

{
  "id":1,
   "name":"Lann",
   "email":"[email protected]"
}

CodePudding user response:

You can archive using map.

let employees = [{
          "id":1,
          "name":"Lann",
          "username":"brot",
          "email":"[email protected]",
          "address":{
             "city":"Gweh",
             "zipcode":"92998-3874",
             "geo":{
                "lat":"45",
                "lng":"77"
             }
          }
          }]
const data = employees.map(o => ({ id: o.id, name: o.name, email:o.email }));
console.log(data[0]);

CodePudding user response:

If your array has only one element you can just access the info, no need to build another array like this: employees[0].id , employees[0].name, employees[0].email or you can just extract an object using Object Destructuring

let employees = [{
  "id": 1,
  "name": "Lann",
  "username": "brot",
  "email": "[email protected]",
  "address": {
    "city": "Gweh",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "45",
      "lng": "77"
    }
  }
}];
const picked = (({ id, name, email }) => ({  id, name, email }))(employees[0]);
console.log(picked);

but if your array has more employees, i think what you need to do is search by id or name and get back just an object with minimal info, you can do that like this

let employees = [{
  "id": 1,
  "name": "Lann",
  "username": "brot",
  "email": "[email protected]",
  "address": {
    "city": "Gweh",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "45",
      "lng": "77"
    }
  }
}];
let employee = employees.find(o => o.name === 'Lann');
let picked = (({ id, name,email }) => ({ id, name,email }))(employee);
console.log(picked);

CodePudding user response:

You cans also loop through your input if it contains multiple items and get an array of shrink items :

let employees = [{
  "id": 1,
  "name": "Lann",
  "username": "brot",
  "email": "[email protected]",
  "address": {
    "city": "Gweh",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "45",
      "lng": "77"
    }
  }
}]

let shrink = [];

for (let employee of employees) {
  shrink.push({
    id: employee.id,
    name: employee.name,
    email: employee.email
  });
}

console.log(shrink);

  • Related