0

I'am trying make an array of object.

var number = 0;
var name = 1;
var dKeyObj = new Object();
//var dKeyPiar = new Object();
var dKeyPiar = [];

function sendFakeData() {
    request(options, function (error, resp, body) {
        dKeyObj['name'] = name.toString(16).padStart(2, '0');  // hexa value
        dKeyObj['value'] = resp.headers['value'];
        dKeyPair[number++] = dKeyObj;
        console.log(dKeyPair[0]);
        if(number < 99)
            making();
        else
            //console.log('lasted data ' + dKeyPair[10]['name']);
            console.log('lasted data ' + dKeyPair[10]);
    });
}

I think the result is...
{ name: '01', value: 'the first value'}
{ name: '01', value: 'the first value'}
{ name: '01', value: 'the first value'}
...
//latest data 0a
latest data { name: '0a', value: 'the tenth value'}

But the log is...
{ name: '01', value: 'the first value'}
{ name: '02', value: 'the second value'}
{ name: '03', value: 'the third value'}
...
//latest data 63
latest data [object, Object]


The index of dKeyPair is ignored.
Can I make an array of object?

1
  • 1
    You have a typo in "dkeyPiar" Commented Jan 15, 2020 at 9:09

2 Answers 2

1
var array = [];
var obj = {};
obj["name"] = "name";
obj["value"] = "val";
array.push(obj);

To push an object into an array we do the above.

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

4 Comments

I tried your code, but the result is same. I don't know what I'm missing...
Plus the code makes sense for the values you are getting.
I got it. I declared the global variable at outside of the function.
I think the push method copy the instance, not value. When I moved the variable inside I got the desired result.
0

You can objects into array:

var dKeyObj1 = {'k1':'v1'};
var dKeyObj2 = {'k2':'v2'};

var arr = new Array();
arr.push(dKeyObj1);
arr.push(dKeyObj2);

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.