I fetch this data from the api
array : { "Blue": 8646, "Red": 3451, "Green": 2342}
then i want to split this into two array
arrayColor : ["Blue", "Red", "Green"]
arrayNumber : [8646, 3451, 2342]
i try using split function but it didn't work, when i check for array.length, console said it undefined.
when i console.log(array)
it show like this
Proxy { "Blue": 8646, "Red": 3451, "Green": 2342}
Help me please.
CodePudding user response:
First, This is not an array it's an object.
You can use Object.keys and Object.value to get data
const obj = { Blue: 8646, Red: 3451, Green: 2342 };
const color = Object.keys(obj);
const value = Object.values(obj);
console.log("color :", color);
console.log("value :", value);
CodePudding user response:
The JSON object contains a key and a value pair. The color is the key and the number is the value. {"key":"value"}
To solve your issue you can do something like this:
let array = {"Blue": 8646, "Red": 3451, "Green": 2342};
let colors = [];
let numbers = [];
for(let key in array) {
console.log(key);
colors.push(key);
numbers.push(array[key]);
}
console.log(colors);
console.log(numbers);
CodePudding user response:
The reason for split function and length not working is because the given data is an object and not a array.split function works only for arrays.The above answers seem to be the correct code.