1

I am querying my db in node and have got the result in the form of an object like this - [ [1234] ].

I want to extract this value and convert it into a string and then pass it onto the client side. I have written the other required code but I am not able to get value from this object. Can anyone help me in getting the value and converting it to string?

3
  • 1
    please post the code you have do with it. Commented Mar 13, 2017 at 7:55
  • it's an array of a single array Commented Mar 13, 2017 at 7:55
  • 1
    Objects in javascript are denoted by {}, what you have is an array []. And it's only element is another array, that again has only one element, a number. so whatever variable you put the result in, let's say foo. You'd just do foo[0][0] and you are done Commented Mar 13, 2017 at 7:56

5 Answers 5

4

Since, the result you've got is a two-dimensional array, you can get the value and convert it into a string (using toString() method) in the following way ...

var result = [ [1234] ];
var string;
result.forEach(function(e) {
  string = e.toString();
});
console.log(string);

** this solution will also work if you have multiple results, ie. [ [1234], [5678] ]

Sign up to request clarification or add additional context in comments.

Comments

2

You have a nested array, meaning that you have an array inside another array:

   [ [1234] ]
// ^-^====^-^

To get the first value of the parent array, use the square brackets: [0]. Remember that indexes start at 0!

If you have val = [[1234]], val[0] gets the enclosed array: [1234]. Then, 1234 is a value in that array (the first value), so you use the square brackets again to get it: val[0][0].

To convert to string, you can use + "" which forces the number to become a string, or the toString() method.

var val = [[1234]];
var str = val[0][0] + "";
//     or val[0][0].toString();

console.log(str, typeof str);

You can read more about arrays here.

Comments

1

var response = [ [1234] ];
console.log(response[0][0]);

Comments

1

to extract values from a string array or an array we can use .toString()

Ex:

let names = ["peter","joe","harry"];
let fname = names.toString();
 output = peter ,joe,harry

or

 let name:string[] = this.customerContacts.map(
 res => res.firstname 
 let fname =name.toString();

Comments

0

Using De-structuring Array concept:

const arr = [[1, 2, 3, 4, 5]];
const [[p, q, r, s, t]] = arr;
console.log(p, q, r, s, t);

Output: 1 2 3 4 5

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.