0

After doing an Sql query, I have an array that looks like the one below. I would like to retrieve only the "name" column in a way that the names are like this: "Name1, Name2, Name3". I have no idea how to do this, I looked on the internet but I find nothing conclusive. Do you have any idea how to retrieve all the data from the "name" column? Thank you in advance.

Array =
[1] {
    id_idx: 1,
    hero_order: 0,
    name: 'Nom1'
},
[2] {
    id_idx: 1,
    hero_order: 0,
    name: 'Nom2'
},
[3]  {
    id_idx: 1,
    hero_order: 0,
    name: 'Nom3'
}

I forgot one information: the array comes from an SQL query rows2[].name.

1
  • 2
    let result=array.map(data=>data.name) Commented Nov 27, 2020 at 10:42

2 Answers 2

1

You can utilize the map function on any JavaScript array, docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Basically a map function tranforms type "A" to type "B". In your case you want to go from the type:

Array<{
    id_idx: number,
    hero_order: number,
    name: string
}>

To:

Array<string>

This can be done with the map function as follows:

const names = myArray.map(a => a.name);
Sign up to request clarification or add additional context in comments.

Comments

0

Following code should give you a working solution -

const result = [{
    id_idx: 1,
    hero_order: 0,
    name: 'Nom1'
},
{
    id_idx: 1,
    hero_order: 0,
    name: 'Nom2'
},
{
    id_idx: 1,
    hero_order: 0,
    name: 'Nom3'
}]

const outputArray = result.map((singleResult) => singleResult.name);

const outputString = outputArray.join(",");

console.log("This will give you an array as output - " + outputArray);

console.log("This will give you string as a output - " + outputString);

console.log('outputArray type:' + typeof outputArray);

console.log('outputString type:' + typeof outputString);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.