0

I know this question was asked many times but i cant get it to work properly as i need. In a node.js ws i push objects into some array like this:

var arr = [];
arr.push({"name": "someName", "id": 12345});

and at the end i send it as a json in the response. How can i push into the array so ill be able to extract data like this ( in the client side ): ** the ID numbers are unique

var name = dataArr[12345];  //will return 'someName'

Im trying to avoid the need to iterate the whole array to get specific values.

1 Answer 1

5

If you want named properties, don't use an Array. Arrays are for ordered data structures accessed by index.

Use an Object instead.

var obj = {};
obj['12345'] = "someName";
Sign up to request clarification or add additional context in comments.

3 Comments

How can i add DYNAMIC values to this? lets say i dont know the values - Im pulling them from a database. For ex: obj['DYNAMIC'] = value;
@user4440845 — Exactly the same way as you use a dynamic variable anywhere. You replace the string literal with a variable containing a string.
I asked that silly question because i had some exception im my code. It works like a charm now. Thank you!

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.