skip to Main Content

I am trying to get some particular property with value from an array object.But it is not working.How to resolve this issue?

var arr1 = [
  {
   name: 'john',
   team: [12, 23, 34],
   sid: 1023,
   options:{boolean:true}
  },
  {
    name: 'john',
    team: [152, 233, 354],
    sid: 1024,
    options:{boolean:true}
   },
  {
   name: 'john',
   team: [152, 273, 314],
   sid: 1025,
   options:{boolean:true}
  },
  ];


 const filteredResult = arr1.find((e) => e.!sid && e.!options);

 console.log(filteredResult);

filteredResult should be like

[
  {
    name: 'john',
    team: [12, 23, 34]
    
  },
  {
    name: 'john',
    team: [152, 233, 354]
  },
  {
    name: 'john',
    team: [152, 273, 314]
  }
];

Demo: https://stackblitz.com/edit/js-73yhgm?file=index.js

3

Answers


  1. You can destructure only the properties you want to be returned.

    const arr1=[{name:"john",team:[12,23,34],sid:1023,options:{boolean:!0}},{name:"john",team:[152,233,354],sid:1024,options:{boolean:!0}},{name:"john",team:[152,273,314],sid:1025,options:{boolean:!0}},];
    const res = arr1.map(({name, team}) => ({name, team}));
    console.log(res);

    Or, with a dynamic array of properties to extract:

    const arr1=[{name:"john",team:[12,23,34],sid:1023,options:{boolean:!0}},{name:"john",team:[152,233,354],sid:1024,options:{boolean:!0}},{name:"john",team:[152,273,314],sid:1025,options:{boolean:!0}},];
    const keys = ['name', 'team'];
    const res = arr1.map(o => Object.fromEntries(keys.map(k => [k, o[k]])));
    console.log(res);
    Login or Signup to reply.
  2. array.map() should do it. Just return the specific properties that you want

    var arr1 = [{
        name: 'john',
        team: [12, 23, 34],
        sid: 1023,
        options: {
          boolean: true
        }
      },
      {
        name: 'john',
        team: [152, 233, 354],
        sid: 1024,
        options: {
          boolean: true
        }
      },
      {
        name: 'john',
        team: [152, 273, 314],
        sid: 1025,
        options: {
          boolean: true
        }
      },
    ];
    
    const result = arr1.map(x => ({
      name: x.name,
      team: x.team
    }))
    
    console.log(result)
    Login or Signup to reply.
  3. arr1.find() will only return the first matching element. Use array filter instead if you want to get all the matching elements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search