Home > Enterprise >  How to store a array into a array in javascript
How to store a array into a array in javascript

Time:11-18

I'm receiving data from a server in the form of an array, which I'm storing in a variable; the data is arriving every 5 seconds, so I need to store every array that comes through the server into an array.

So the array looks like this:

array

It's saved in a variable, and I'm setting it to log every 5 seconds, so all the different data is getting logged.

So I need to get it stored in an array. This is the variable from which the array is coming; here is my code: 

setInterval(function() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var myObj = this.responseText;
            snifferOnServer(myObj);
        }
    };
    xhr.open('GET', 'http://192.168.43.154/wifimac', true);
    xhr.send();
}, 7000);

function snifferOnServer(x) {
    let obj = x.split(']');
    // console.log(obj);
    for (let i = 0; i < obj.length; i  ) {
        mac = obj[i];
        macIdData = mac.split(',');
        console.log(macIdData);
    }
}

The array I was seeing in the console was getting through macIdData. I need to store all of the data in a new array The macIdData is a 2 dimensional array.

Thank You.

Need to store a variable which consist of array into a new array.

CodePudding user response:

*Editing because i accidentally pressed submit

array = [...array, yourArray]

let array = [];

for (let i = 0; i < 5; i  ) {
  array = [...array, [1,2,3,4,5]];
}
console.log(array);

CodePudding user response:

you can try this out. Also it's best to use JavaScript methods to parse your data-set.

// Sample of API data
let rawData = JSON.stringify([
    ["1234", "45678", "9"],
    ["abc", "def", "ghi"],
    ["ABC", "DEF", "GHI"]
])

snifferOnServer(rawData);

function snifferOnServer(data) {
    let obj = JSON.parse(data);
    let macIdData = [];

    // Loop through the obj dataset
    obj.forEach((mac) => {
        // Loop through the mac dataset
        mac.forEach((items) => {
            // store each value in the mac Array
            macIdData.push(items);
        })
    });

    console.log(macIdData);
};
  • Related