Reputation: 155
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])
}
}
Upvotes: 7
Views: 4031
Reputation: 19090
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);
Upvotes: 2
Reputation: 38565
The following code should solve your problem
var phones = {};
var max;
Object.entries(data).forEach(function (entry) {
if (entry[0] == "Maxvalue") {
max = entry[1];
}
else {
phones[entry[0]] = entry[1];
}
});
console.log("Phones: ", phones);
console.log("Max: ", max)
Upvotes: 0
Reputation: 44145
Just extract the Maxvalue
property, and assign the others to Cellphone
. This is really simple with destructuring and spreading:
const data = {
Vivo: {
Time: [20190610, 20190611],
Price: [2000, 2000]
},
Huawei: {
Time: [20190610, 20190611],
Price: [3000, 3000]
},
Maxvalue: 3000
};
const { Maxvalue: Max, ...Cellphone } = data;
console.log("Max:", Max);
console.log("Cellphone:", Cellphone);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Upvotes: 2
Reputation: 3578
You can individually pick out the max value, save it in to a variable, then remove it from the object. This will allow you to assign all cellphones to a variable, even if their names change. For example;
let data = {
Vivo:{Time:[20190610,20190611],Price:[2000,2000]},
Huawei:{Time:[20190610,20190611],Price:[3000,3000]},
Maxvalue:3000
}
// save the maxValue key
let maxValue = data.Maxvalue;
// then remove it from the object
delete(data.Maxvalue);
// the remaining keys are cellphones
let cellPhones = data;
console.log(maxValue, cellPhones);
Upvotes: 1
Reputation: 75
In the function, where you set Data
as a parameter, do the following
let Cellphone = {
Vivo: Data.Vivo,
Huawei: Data.Huawei
};
let Max = Data.Maxvalue;
Upvotes: 0