简体   繁体   中英

How to Extract fields from array?

 let obj = [{ first: 'Jane', last: 'Doe' , x : 1 }, { first: 'Jane1', last: 'Doe1', x : 2 }, { first: 'Jane2', last: 'Doe2', x : 3 }, { first: 'Jane3', last: 'Doe4' , x : 4}]; // gives false for unsatisfied condition, which is fine I believe let res = obj.map( o => { return ox > 2 && { "first": o.first, "x": ox } } ) // below returns all fields where as I want only two fields let res1 = obj.filter( o => { return ox > 2 && { "first": o.first, "x": ox } } ) console.log(res) console.log(res1) 

How to get first and x fields with condition

Expected output

[
   {
    "first": "Jane2",
    "x": 3
  },
  {
    "first": "Jane3",
    "x": 4
  }
]

Thanks

You can use .reduce to form an array of objects where x is greater than 2 like so. Here I have used destructuring assignment to get the first and x property from the given object, and then used a ternary operator to check whether or not to add the object to the array:

 const arr = [{first:'Jane',last:'Doe',x:1},{first:'Jane1',last:'Doe1',x:2},{first:'Jane2',last:'Doe2',x:3},{first:'Jane3',last:'Doe4',x:4}], res = arr.reduce((acc, {first, x}) => x > 2 ? [...acc, {first, x}]:acc, []); console.log(res); 

Just concat the 2 functions

 const arr = [ { first: 'Jane', last: 'Doe', x: 1 }, { first: 'Jane1', last: 'Doe1', x: 2 }, { first: 'Jane2', last: 'Doe2', x: 3 }, { first: 'Jane3', last: 'Doe4', x: 4 } ]; const result = arr.filter(o => ox > 2).map(o => ({first: o.first, x: ox})); console.log(result); 

You can use filter to get a new array based on your criteria. This is useful since it does not modify your existing array. You can then use map to modify the structure as shown.

 const arr = [{ first: 'Jane', last: 'Doe', x: 1 }, { first: 'Jane1', last: 'Doe1', x: 2 }, { first: 'Jane2', last: 'Doe2', x: 3 }, { first: 'Jane3', last: 'Doe4', x: 4 } ], res = arr.filter(item => item.x > 2).map(({first,x}) => ({first,x})); console.log(res); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM