Home > OS >  Returing just the value from an array of objects
Returing just the value from an array of objects

Time:10-11

So I am running a NodeJS Serverless instance, using Knex.js as my DB middleware. When attempting to return JUST the value from a request to Knex, I always get [ { vrn: 'xx12xyz' } ]. I have tried using Object(), does anyone have a quick one liner or small helper function that can help me flatten this into a direct array such that I can pick out JUST the value?

This is the code I am using:

const vrnList = await db('vehicles').select('vrn').where('id', '=', '1');
    console.log("The quick car with the VRN ", Object.values(vrnList), " overtook me on the freeway");

TL;DR: Splitting the object and array id from the values

CodePudding user response:

Try this one:

let onlyValues = vrnList.map(result => result.vrn);

CodePudding user response:

Since the OP seems to retrieve the value(s) key agnostic via Object.values which returns an array of values, the OP in addition needs to utilize flatMap ...

console.log(
  [{ vrn: 'xx12xyz' } ].flatMap(item => Object.values(item))
);
console.log(
  [
    { vrn: 'xx12xyz' },
    { vrn: 'xx98abc' },
    { vrn: 'yy34xyz' },
  ].flatMap(item => Object.values(item))
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

  • Related