2

I am trying to work with a pretty simple data structure but just cant get it right.

I have an array which looks like that :

[{"object":"name","context":"..."},{"object":"name","context":"..."}]

Assume this structure is kept in a variable names object_list

All I want is to add an additional field in the base structure so my object will looks like :

[{"object":"name","context":"..."},{"object":"name","context":"..."}],
additional_data : "data"

in context of code I would like to be able to :

var item = object_list[0];
var additional_data = object_list.additional_data;

cant find a way to add to my array that extra field.

1
  • You can have an object inside an array or an array in an object, but an object can't be an array and vice-versa. I think you're mixing it up a little too much Commented Mar 31, 2014 at 13:15

3 Answers 3

3

Well, if you currently have the array:

var object_list = [{"object":"name","context":"..."},{"object":"name","context":"..."}];

You need a new object, with that as a property, and another property:

var newObj = {
    object_list: object_list,
    additional_data: "data"
}

Then you can do:

newObj.object_list; //array
newObj.additional_data; //your data

Important side note, since JS objects are just references, changing anything in object_list will also be reflected in newObj.object_list

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

3 Comments

This is what I am trying to avoid.. in your suggestion to reach the additional data I need to do newObj.additional_data and to reach the array i need newObj.object_list. I want to be able to reach the additional_data through object_list.additional_data.
@Nuno_147 -- You can't. That's not a valid JS object [], key: val. The proper is { key: [], key: val }
so to correct it I basically need to name my list in the structure, right ?
1

Is this what you are looking for?

var object_list = [{"object":"name","context":"..."}];
object_list.additional_data = "data";

http://jsfiddle.net/V3yDb/

1 Comment

Seems to work. it doesn't work on my case for some reason, but it does "solve" what I tried to get.
0

Actually you can do followings with JS arrays. They are all valid but strange.

var object_list = [{"object":"name","context":"..."},{"object":"name","context":"..."}];

object_list.field1 = 'some value';

object_list['field2'] = 'some other value';

Then you can use object_list as usual array and also as an object. Below are the same.

object_list.field1

object_list['field1']

It is like a map with different types of keys, in your case integer and string.

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.