Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Object - Different Type Depending on Context

Tags:

javascript

I am going to start off by saying that I don't think this is possible, but hoping that someone knows some special way in JavaScript to do this. I have a JavaScript object defined as follows:

var t = {
  "fields": {
    "a": ["99", "98"]
  }
};

I am looking for a way so that I can define the same element of an array twice with different values that could be used in two different contexts - something like this:

var t = {
  "fields": {
    "a": ["99", "98"],
    "a": "99|98"
  }
};

If I was to query it using the syntax t.fields["a"] it would return "99|98" but if I was to query it using t.fields["a"][0] then it would return "99". I understand if I query an array without specifying an index then it returns "99,98" as a string - but I need it to return the entries delimited with a "|" instead of a ",".

like image 843
chrixm Avatar asked Nov 01 '14 09:11

chrixm


People also ask

What is context object in JavaScript?

What is context? Context is always the value of the this keyword which is a reference to the object that “owns” the currently executing code or the function where it's looked at. We know that window is a global object in the browser so if we type this in the console and it should return window object, which it does.

What are three types of objects supported by JavaScript?

Data Types in JavaScriptObject, Array, and Function (which are all types of objects) are composite data types. Whereas Undefined and Null are special data types.

How do you iterate over an object in JavaScript?

There are two methods to iterate over an object which are discussed below: Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object.


1 Answers

It's also possible to use a getter function, like this:

var t = {
    "fields": {
        "_a": ["99", "98"],
        "a": function (index) {
            if (typeof index != 'undefined')
                return this._a[index];
            else
                return this._a.join('|');
        }
    }
};

console.log(t.fields['a']()); // 99|98
console.log(t.fields['a'](1));// 98

You can also have a global get function for all the fields:

var t = {
    "fields": {
        "_a": ["99", "98"],
        get: function (field, index) {
            if (typeof index != 'undefined')
                return this['_' + field][index];
            else
                return this['_' + field].join('|');
        }
    }
};

console.log(t.fields.get('a')); // 99|98
console.log(t.fields.get('a', 1)); // 98
like image 195
Exlord Avatar answered Oct 15 '22 18:10

Exlord