Creating array-like objects in JavaScript - javascript

In JavaScript, there are objects that pretend to be arrays (or are "array-like"). Such objects are arguments, NodeLists (returned from getElementsByClassName, etc.), and jQuery objects.
When console.logged, they appear as arrays, but they are not. I know that in order to be array-like, an object must have a length property.
So I made an "object" like this:
function foo(){
this.length = 1;
this[0] = "bar";
}
var test = new foo;
When I console log(test), I get (as expected) a foo object. I can "convert" it to an array using
Array.prototype.slice.call(test)
But, I don't want to convert it, I want it to be array-like. How do I make an array-like object, so that when it's console.logged, it appears as an array?
I tried setting foo.prototype = Array.prototype, but console.log(new foo) still shows a foo object, and not an array.

Depends specifically on the console. For custom objects in Chrome's developer console, and Firebug you'll need both the length and splice properties. splice will also have to be a function.
a = {
length: 0,
splice: function () {}
}
console.log(a); //[]
It's important to note, however, that there is no official standard.
The following code is used by jQuery (v1.11.1) internally to determine if an object should use a for loop or a for..in loop:
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
Note that it's possible to have an object that appears in the console as an array ([]) but that gets iterated over with a for..in loop in jQuery, or an object that appears as an object in the console ({}) but that gets iterated over with a for loop in jQuery.

The same question got into my mind as while we can use array like arguments parameter:
function arrayLike() {
console.log(typeof arguments)
console.log(arguments)
console.log(Array.from(arguments))
}
arrayLike(1,2,3)
So, let's try creating our own array-like object:
let arrayLikeObject = {
0: 1,
1: 2
}
console.log(Array.from(arrayLikeObject))
Obviously, there's no length property defined so our arrayLikeObject will only return an empty array. Now, let's try defining a length property:
let arrayLikeObject = {
length: 2,
0: 1,
1: 2
}
console.log(Array.from(arrayLikeObject))
What if length is set different?
let arrayLikeObject = {
length: 1,
0: 1,
1: 2
}
console.log(Array.from(arrayLikeObject))
// it will only return the value from first `0: 1`
let arrayLikeObject = {
length: 5,
0: 1,
1: 2
}
console.log(Array.from(arrayLikeObject))
// other 3 values will be printed as undefined
But, I don't want to convert it...
You actually wanted to create an array, not array-like object. The array-like object must be converted like you said:
Array.prototype.slice.call(arrayLikeObject)
// Or,
[].slice.call(arrayLikeObject)
If you do try to use array methods on array-like object, then you'll get type error:
let arrayLikeObject = {
length: 5,
0: 1,
1: 2
}
console.log(arrayLikeObject.sort())
Thus, to use the array methods on arrayLikeObject, we need to convert it into array as we did in preceding examples using Array.from.
Otherwise, you simply need to create an array:
let arr = [1,2] // I don't mean, you don't know
Other consideration:
You can't use it as constructor:
let arrayLikeObject = {
length: 1,
slice: function () {
return 1
}
}
console.log(new arrayLikeObject) // Type error
In the following snippet, the result will be [undefined] as the length property is set to 1 but there's no 0 indexed property:
let arrayLikeObject = {
length: 1,
slice: function () {
return 1
}
}
console.log(Array.from(arrayLikeObject))
But if you set the length to 0, then the result will be an empty array [] because we're telling that we don't have any values in this array-like object.

Is this any use: extended array prototype, seems like he's doing what you did and creating the prototype as an array, but including an extra method (that may or may not work, I've not tested this):
var MyArray = function() {
};
MyArray.prototype = new Array;
MyArray.prototype.forEach = function(action) {
for (var i = 0, l=this.length; i < l, ++i) {
action(this[i]);
}
};
Hope it helps in some way.

Look at this :
var ArrayLike = (function () {
var result;
function ArrayLike(n) {
for (var idx = 0; idx < n; idx++) {
this[idx] = idx + 1;
}
// this.length = Array.prototype.length; THIS WILL NOT WORK !
}
// ArrayLike.prototype.splice = Array.prototype.splice; THIS WILL NOT WORK !
// THIS WILL WORK !
Object.defineProperty(ArrayLike.prototype, 'length', {
get: function() {
var count = 0, idx = 0;
while(this[idx]) {
count++;
idx++;
}
return count;
}
});
ArrayLike.prototype.splice = Array.prototype.splice;
ArrayLike.prototype.multiple = function () {
for (var idx = 0 ; idx < this.length ; idx++) {
if (result) {
result = result * this[idx];
} else {
result = this[idx];
}
}
return result;
};
return ArrayLike
})();
var al = new ArrayLike(5);
al.__proto__ = ArrayLike.prototype;
console.log(al.length, al.multiple(), al);
This will display in Chrome : 5 120 [1, 2, 3, 4, 5]

I think this is what you are looking for.
Override the toString function.
foo.prototype.toString = function()
{
return "[object Foo <" + this[0] +">]";
}

Related

How to "splice" an object?

Here is what I want to achieve:
A function called Splice which can take 3 arguments:
The first is an object.
The second is numeric.
The third is numeric.
It takes properties from an object and uses them for a newly created object.
Which properties are defined by the two numbers. The second argument indicates the position of the key/value pair that I want to start taking properties from and the third indicates how many I want to remove.
So for instance splice(0,2) refers to the positions 0 and 1 of the object having the following object: var obj = {a: 1, b: 2, c: 2} and calling the function splice with the arguments obj, 0, 2 should return {a: 1, b: 2}
If the third argument is not passed it should default to 1.
This is what I have so far (not yet respecting the last part when only one number is passed in):
function splice(object, number, number2) {
var newOjb = {};
var count = 0;
object.forEach(function(element, index) {
count++;
if(count <= number2 && count > number) {
newObj[key]=item
} else if (number == count) {
newObj[key]=item
}
})
return newObj;
}
However, I seem to use some wrong syntax as my console tells me my forEach loop is not a function and the code, in general, doesn't seem to work.
Any ideas for basic solutions (no fancy techniques)?
Use Object.entries(object).forEach(function([key, item], index) { (Note: This will not guarantee order). You have also typo in var newOjb = {};
P.S. You don't need that count, you can use index in your conditions
number - index, number2 - count
function splice(object, number, number2) {
var newObj = {};
if (!number2) {
number2 = 1;
}
Object.entries(object).forEach(function([key, item], index) {
if (index >= number && index - number < number2) {
newObj[key] = item
}
})
return newObj;
}
let obj = {
a: 1,
b: 2,
c: 2
};
console.log(splice(obj, 0, 2))
console.log(splice(obj, 2))
console.log(splice(obj, 1, 2))
FWIW, here's a function that behaves exactly like Array.splice for objects (don't know if this qualifies as "fancy" though):
function spliceObject(obj, start, deleteCount, ...items) {
let e = Object.entries(obj);
let r = e.splice(start, deleteCount, ...items.flatMap(Object.entries));
Object.keys(obj).forEach(k => delete obj[k]);
e.forEach(([k, v]) => obj[k] = v);
return Object.fromEntries(r);
}
//
obj = {a:1, b:2, c:3, d:4, e:5, f:6 }
ret = spliceObject(obj, 1, 3, {xyz:88}, {blah:99})
console.log(obj)
console.log(ret)
Do note however that you generally shouldn't rely on object properties being ordered in any particular way. The ordering is defined and mandated by the standard, but not all engines and tools get it right.
For your default value question, this is a pattern that works well
function myfunction1(val) {
this.val = val ? val : 1;
console.log(this.val);
}

Creating a efficient function that create one flat array from all values of all objects

I need a function in javascript that get all values from all kinds of objects and store in one single level array. I don't need its keys just values, but needs search for values recursively inside objects (HTMLElement and functions are considered a value, see tests for an example).
IMPORTANT - I'm not asking for transform arguments object into array. I want all values no matter how deep it is.
I've already wrote a function, but I want to know, if there is more effective way.
Javascript Code
//Helper function
function isString(obj){
return (typeof obj === 'string' || obj instanceof String);
}
//Main function
function toArray(obj) {
var k = Object.keys((obj || 0));
var i = 0, l = k.length;
if (isString(obj) || l == 0 || obj === window) {
return obj;
} else {
var objs = [];
while (i < l) {
objs = objs.concat(toArray(obj[k[i]]));
i++;
}
return objs
}
}
Tests
var i, out,
arr = [{0: 2, 'car': 3}, {1: function(){}, 2:function foo(){}}, 1 ,'bar' , document.body, document.querySelectorAll('body'), window];
var s = performance.now();
for (i = 0; i < 10000; i++) {
out = toArray(arr);
}
var e = performance.now();
//out: [2, 3, function, function, 1, "bar", <body>, <body>, 1, Window] (10)
//Passed in ~185ms (Safari 9.0.3)

Drop last element of javascript array when array reaches specific length

I would like to cache some data in javascript, but the cache should be limited to 10 elements for example.
I can place the objects in javascript array, but what is the best way to keep the array limited to 10 elements?
Example:
function getData(dataId) { return new NextDataObject(dataId); }
var array = new Array();
array.push(getData(0));
array.push(getData(1));
(...)
array.push(getData(10)); // this should result in dropping "oldest" data, so getData(0) should be removed from the array, so that in array there are only 10 objects at maximum
Should such mechanism be written manually (using splice() for example?) or are there better ways to achieve such "cache" structure in javascript?
BTW: in this particular situation I'm using angular.
Override the push function of your caching array.
var array = new Array()
array.push = function (){
if (this.length >= 10) {
this.shift();
}
return Array.prototype.push.apply(this,arguments);
}
Plunker
To make this more reusable I created a method which returns new instance of such array (basing on above code).
function getArrayWithLimitedLength(length) {
var array = new Array();
array.push = function () {
if (this.length >= length) {
this.shift();
}
return Array.prototype.push.apply(this,arguments);
}
return array;
}
var array = getArrayWithLimitedLength(10);
To remove first element from array use shift:
if (arr.length > 10) {
arr.shift(); // removes the first element from an array
}
How about this object?
function Cache(maxLength) {
this.values = [];
this.store = function(data) {
if(this.values.length >= maxLength) {
this.getLast();
}
return this.values.push(data);
}
this.getLast = function() {
return this.values.splice(0,1)[0];
}
}
cache = new Cache(3);
// => Cache {values: Array[0]}
cache.store(1)
// => 1
cache.store(2)
// =>2
cache.store(3)
// => 3
cache.store(4)
// =>3
cache.values
// => [2, 3, 4]
cache.getLast()
// => 2
cache.values
[3, 4]
You could create new method in Array.prototype to mimic your needs.
Array.prototype.push_with_limit = function(element, limit){
var limit = limit || 10;
var length = this.length;
if( length == limit ){
this.shift();
}
this.push(element);
}
var arr = []
arr.push_with_limit(4); // [4]
arr.push_with_limit(9); // [4, 9]
....
// 11th element
arr.push_with_limit(3); // [9, ..., 3] 10 elements
Simple fixed length queue:
Array.prototype.qpush = function( vals, fixed ) {
if (arguments.length) {
if (Array.isArray(vals)) {
for (var v of vals) {
this.push(v);
}
} else {
this.push(vals);
}
var _f = (typeof this.fixed != undefined) ? this.fixed : 0;
if (typeof fixed != undefined) {
_f = (Number(fixed)===fixed && fixed%1===0 ) ? fixed : _f;
}
this.fixed = _f;
if (this.fixed>0) this.splice(0, this.length - _f);
}
}
var q = new Array();
q.push(0);
q.qpush( [1, 2, 3], 10 );
q.qpush( [4] );
q.qpush( 5 );
q.qpush( [6, 7, 8, 9, 10, {k:"object"} ] );
console.log(q);
if(array.length == 10) {
array.splice(0, 1);
// this will delete first element in array
}
If you do a check whether the array has reached 10 entries with array.length, just remove the first element before pushing a new element. This can be done several ways as Tushar states, array.shift() would be the fastest, but you can indeed use array.splice() aswell.
It would look like this:
if(array.length > 10) {
array.shift();
array.push(getData(10));
}
On a side note, instead of using var array = new Array() I suggest you simply use var array = [];. This is because the new keyword in Javascript sometimes has bad side effects. If you for example want to create an array with 1 element being a digit, and you use var arr = new Array(12);, an array with 12 undefined elements will be created. Whereas var arr = [12]; will create an array with 1 element, the digit 12.
But I guess that's a minor thing to consider..
You could use an object instead...
var obj = {}; //your cache object
obj[window.performance.now()] = getData(val); //add value, index by microsecond timestamp
if(Object.keys(obj).length > 10){ // then if the length ever gets bigger than 10..
var array = Object.keys(obj).sort(); //sort the properties by microsecond asc
delete obj[array[0]]; //delete the oldest one
}
Here is a jsFiddle example showing how it works: https://jsfiddle.net/uhkvk4mw/
just check if the length is reached then pop it
if(arr.length > someNumber){
arr.pop(); // pop() will remove the last element
}

How to sum the values of a JavaScript object?

I'd like to sum the values of an object.
I'm used to python where it would just be:
sample = { 'a': 1 , 'b': 2 , 'c':3 };
summed = sum(sample.itervalues())
The following code works, but it's a lot of code:
function obj_values(object) {
var results = [];
for (var property in object)
results.push(object[property]);
return results;
}
function list_sum( list ){
return list.reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
}
function object_values_sum( obj ){
return list_sum(obj_values(obj));
}
var sample = { a: 1 , b: 2 , c:3 };
var summed = list_sum(obj_values(a));
var summed = object_values_sum(a)
Am i missing anything obvious, or is this just the way it is?
It can be as simple as that:
const sumValues = obj => Object.values(obj).reduce((a, b) => a + b, 0);
Quoting MDN:
The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
from Object.values() on MDN
The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
from Array.prototype.reduce() on MDN
You can use this function like that:
sumValues({a: 4, b: 6, c: -5, d: 0}); // gives 5
Note that this code uses some ECMAScript features which are not supported by some older browsers (like IE). You might need to use Babel to compile your code.
You could put it all in one function:
function sum( obj ) {
var sum = 0;
for( var el in obj ) {
if( obj.hasOwnProperty( el ) ) {
sum += parseFloat( obj[el] );
}
}
return sum;
}
var sample = { a: 1 , b: 2 , c:3 };
var summed = sum( sample );
console.log( "sum: "+summed );
For fun's sake here is another implementation using Object.keys() and Array.reduce() (browser support should not be a big issue anymore):
function sum(obj) {
return Object.keys(obj).reduce((sum,key)=>sum+parseFloat(obj[key]||0),0);
}
let sample = { a: 1 , b: 2 , c:3 };
console.log(`sum:${sum(sample)}`);
But this seems to be way slower: jsperf.com
If you're using lodash you can do something like
_.sum(_.values({ 'a': 1 , 'b': 2 , 'c':3 }))
Now you can make use of reduce function and get the sum.
const object1 = { 'a': 1 , 'b': 2 , 'c':3 }
console.log(Object.values(object1).reduce((a, b) => a + b, 0));
A regular for loop is pretty concise:
var total = 0;
for (var property in object) {
total += object[property];
}
You might have to add in object.hasOwnProperty if you modified the prototype.
Honestly, given our "modern times" I'd go with a functional programming approach whenever possible, like so:
const sumValues = (obj) => Object.keys(obj).reduce((acc, value) => acc + obj[value], 0);
Our accumulator acc, starting with a value of 0, is accumulating all looped values of our object. This has the added benefit of not depending on any internal or external variables; it's a constant function so it won't be accidentally overwritten... win for ES2015!
Any reason you're not just using a simple for...in loop?
var sample = { a: 1 , b: 2 , c:3 };
var summed = 0;
for (var key in sample) {
summed += sample[key];
};
http://jsfiddle.net/vZhXs/
let prices = {
"apple": 100,
"banana": 300,
"orange": 250
};
let sum = 0;
for (let price of Object.values(prices)) {
sum += price;
}
alert(sum)
I am a bit tardy to the party, however, if you require a more robust and flexible solution then here is my contribution. If you want to sum only a specific property in a nested object/array combo, as well as perform other aggregate methods, then here is a little function I have been using on a React project:
var aggregateProperty = function(obj, property, aggregate, shallow, depth) {
//return aggregated value of a specific property within an object (or array of objects..)
if ((typeof obj !== 'object' && typeof obj !== 'array') || !property) {
return;
}
obj = JSON.parse(JSON.stringify(obj)); //an ugly way of copying the data object instead of pointing to its reference (so the original data remains unaffected)
const validAggregates = [ 'sum', 'min', 'max', 'count' ];
aggregate = (validAggregates.indexOf(aggregate.toLowerCase()) !== -1 ? aggregate.toLowerCase() : 'sum'); //default to sum
//default to false (if true, only searches (n) levels deep ignoring deeply nested data)
if (shallow === true) {
shallow = 2;
} else if (isNaN(shallow) || shallow < 2) {
shallow = false;
}
if (isNaN(depth)) {
depth = 1; //how far down the rabbit hole have we travelled?
}
var value = ((aggregate == 'min' || aggregate == 'max') ? null : 0);
for (var prop in obj) {
if (!obj.hasOwnProperty(prop)) {
continue;
}
var propValue = obj[prop];
var nested = (typeof propValue === 'object' || typeof propValue === 'array');
if (nested) {
//the property is an object or an array
if (prop == property && aggregate == 'count') {
value++;
}
if (shallow === false || depth < shallow) {
propValue = aggregateProperty(propValue, property, aggregate, shallow, depth+1); //recursively aggregate nested objects and arrays
} else {
continue; //skip this property
}
}
//aggregate the properties value based on the selected aggregation method
if ((prop == property || nested) && propValue) {
switch(aggregate) {
case 'sum':
if (!isNaN(propValue)) {
value += propValue;
}
break;
case 'min':
if ((propValue < value) || !value) {
value = propValue;
}
break;
case 'max':
if ((propValue > value) || !value) {
value = propValue;
}
break;
case 'count':
if (propValue) {
if (nested) {
value += propValue;
} else {
value++;
}
}
break;
}
}
}
return value;
}
It is recursive, non ES6, and it should work in most semi-modern browsers. You use it like this:
const onlineCount = aggregateProperty(this.props.contacts, 'online', 'count');
Parameter breakdown:
obj = either an object or an array
property = the property within the nested objects/arrays you wish to perform the aggregate method on
aggregate = the aggregate method (sum, min, max, or count)
shallow = can either be set to true/false or a numeric value
depth = should be left null or undefined (it is used to track the subsequent recursive callbacks)
Shallow can be used to enhance performance if you know that you will not need to search deeply nested data. For instance if you had the following array:
[
{
id: 1,
otherData: { ... },
valueToBeTotaled: ?
},
{
id: 2,
otherData: { ... },
valueToBeTotaled: ?
},
{
id: 3,
otherData: { ... },
valueToBeTotaled: ?
},
...
]
If you wanted to avoid looping through the otherData property since the value you are going to be aggregating is not nested that deeply, you could set shallow to true.
Use Lodash
import _ from 'Lodash';
var object_array = [{a: 1, b: 2, c: 3}, {a: 4, b: 5, c: 6}];
return _.sumBy(object_array, 'c')
// return => 9
I came across this solution from #jbabey while trying to solve a similar problem. With a little modification, I got it right. In my case, the object keys are numbers (489) and strings ("489"). Hence to solve this, each key is parse. The following code works:
var array = {"nR": 22, "nH": 7, "totB": "2761", "nSR": 16, "htRb": "91981"}
var parskey = 0;
for (var key in array) {
parskey = parseInt(array[key]);
sum += parskey;
};
return(sum);
A ramda one liner:
import {
compose,
sum,
values,
} from 'ramda'
export const sumValues = compose(sum, values);
Use:
const summed = sumValues({ 'a': 1 , 'b': 2 , 'c':3 });
We can iterate object using in keyword and can perform any arithmetic operation.
// input
const sample = {
'a': 1,
'b': 2,
'c': 3
};
// var
let sum = 0;
// object iteration
for (key in sample) {
//sum
sum += (+sample[key]);
}
// result
console.log("sum:=>", sum);
A simple solution would be to use the for..in loop to find the sum.
function findSum(obj){
let sum = 0;
for(property in obj){
sum += obj[property];
}
return sum;
}
var sample = { a: 1 , b: 2 , c:3 };
console.log(findSum(sample));
function myFunction(a) { return Object.values(a).reduce((sum, cur) => sum + cur, 0); }
Sum the object key value by parse Integer. Converting string format to integer and summing the values
var obj = {
pay: 22
};
obj.pay;
console.log(obj.pay);
var x = parseInt(obj.pay);
console.log(x + 20);
function totalAmountAdjectives(obj) {
let sum = 0;
for(let el in obj) {
sum += el.length;
}
return sum;
}
console.log(totalAmountAdjectives({ a: "apple" }))
A simple and clean solution for typescrip:
const sample = { a: 1, b: 2, c: 3 };
const totalSample = Object.values(sample).reduce(
(total: number, currentElement: number) => total + currentElement
);
console.log(totalSample);
Good luck!

Recognize the last iteration in a Javascript object

I have an object that I'm iterating
for (el in object) {
// Some work here
}
I want to know when is the last iteration, inside the iteration, so I can do
for (el in object) {
// Some work here
if (last_iteration) {
// Do something
}
}
Any straightforward way to do it?
I know I'm late but I just ran into this and fixed it like this:
let i = 0;
const object = { a: 1, b: 2 };
const length = Object.keys(object).length;
for (el in object) {
const last = i === length - 1; // true if last, false if not last
console.log(i, el, last);
i++;
}
Update: A few years later, i++ at the end of a loop really irks me.
const object = { a: 1, b: 2 };
const length = Object.keys(object).length;
for (const [key, isLast] of Object.keys(object)
.map((key, i) => [key, i === length - 1])) {
console.log(key, isLast);
}
or
const object = { a: 1, b: 2 };
const length = Object.keys(object).length;
Object.keys(object)
.map((key, i) => [key, i === length - 1]))
.map(([key, isLast]) => {
console.log(key, isLast);
})
You can do something like this:
var first = true;
var prev;
for (var el in object) {
// Some work here
if (first) {
first = false;
} else {
doSomething(prev, object[prev]);
}
prev = el;
}
if (prev !== undefined) { // There was at least one element
doSomethingElse(prev, object[prev]); // Prev is now last of all elements
}
This is in case you want to process all but the last element in one way (doSomething) and process the last element in another way (doSomethingElse).
If you want to process all the elements in one way (doSomething) and want to have extra processing for the last element only (doSomethingExtra), you can do:
var prev;
for (var el in object) {
// Some work here
doSomething(el, object[el]);
prev = el;
}
if (prev !== undefined) { // There was at least one element
doSomethingExtra(prev, object[prev]); // Prev is now last of all elements
}
To make it even shorter, you can do similar to what Török Gábor did in the gist he provided, by reusing el variable, i.e.:
var el;
for (el in object) {
// Some work here
doSomething(el, object[el]);
}
if (el !== undefined) { // There was at least one element
doSomethingExtra(el, object[el]); // El is now last of all elements
}
Hope this helps.
If the keys are not numerical, this works:
let anObject = {'one': 1, 'two': 2, 'three': 3, 'lastKey': 4};
let objectKeys = Object.keys(anObject);
let lastObjectKey = objectKeys.slice(-1).toString();
console.log(lastObjectKey); // 'lastKey'
The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
Example with numerical keys causing reordering:
let anObject2 = {3: 3, 2: 2, 'notLastKey': 4, 1: 'lastKey'};
let objectKeys2 = Object.keys(anObject2);
console.log(objectKeys2); // ["1", "2", "3", "notLastKey"]
let lastObjectKey2 = objectKeys2.slice(-1).toString();
console.log(lastObjectKey2); // "notLastKey"
Note that this will only work if the object you are iterating over is an array (has numeric keys)
var a = [1,2,3,4,5];
for (i in a) {
if(a[+i+1] === undefined)
console.log('the last one is: ' + a[i]);
}
Note that the + sign before i is necessary since if omitted, it will do a string concatenation, the keys resulting in 01, 12, 23, etc
as said already, there is no distinct order for properties, so last enumerated property is only known afterwards.
var object = { a: 'b', c: 42 };
for ( var string in object ) ;
alert( object[string] ); // last property name is still here

Categories