Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate a json data in javascript

I am very new to js, now i have a json data which was passed by backend to my js file. The json data is like the following:

{
Vivo:{Time:[20190610,20190611],Price:[2000,2000]},
Huawei:{Time:[20190610,20190611],Price:[3000,3000]},
Maxvalue:3000
}

the json data i get is by the following code:

fetch('/Tmall') //Tmall is the url i go to fetch data
.then(function(response) {
return response.json();
}).then(function(Data) {

...
}

Next I will process the data to present at the front-end, but i don't know how to assign the Data to two different argument:

Cellphone = 
{
Vivo:{Time:[20190610,20190611],Price:[2000,2000]},
Huawei:{Time:[20190610,20190611],Price:[3000,3000]}
}

Max = {Maxvalue:3000}

Here is what i tried to do, i used if-is the key to separate the data from the original one, but it dosen't work

    var Cellphone = {}
    for (var i = 0; i < Data.length; i++)
    {
      if (Data.key[i] != 'Maxvalue'){
        Cellphone.push(Data[i])
      }
    }
like image 467
Tilei Liu Avatar asked Jun 11 '19 08:06

Tilei Liu


1 Answers

You can use Object.keys() combined with Array.prototype.filter() and Array.prototype.map().

Code:

// Your `Data` response...
const Data = {Vivo:{Time:[20190610,20190611],Price:[2000,2000]},Huawei:{Time:[20190610,20190611],Price:[3000,3000]},Maxvalue:3000};

// Logic
const Cellphone = Object.keys(Data)
  .filter(k => k !== 'Maxvalue')
  .map(k => ({ [k]: Data[k] }));
const Max = { Maxvalue: Data.Maxvalue };

console.log('Cellphone:', Cellphone);
console.log('Max:', Max);
like image 189
Yosvel Quintero Arguelles Avatar answered Sep 21 '22 21:09

Yosvel Quintero Arguelles