How do Ioop through some JSON and get particular key value - javascript

I'm new to JavaScript and im confused how to extract a particular key value from a JSON file:
var me = {"fcolors": ["blue", "green", "whitesmoke"],"fire": ["pink", "grey", "red"]};
i want only fcolour values
fcolour = [];
for (var key in me) {
if (me[key] instanceof Array) {
for (var i = 0; i < me[key].length; i++) {
console.log();
fcolour.push(me[key][i])
}
}
}
i want result to be fcolour=["blue", "green", "whitesmoke"]
thanks in advance and any comment is appreciated.....

You dont need to loop to get its value since your json doesnt have array of fcolors:
me.fcolors will give you ["blue", "green", "whitesmoke"]
Plunker Here
For Multiple objects:
var data = [{
"fcolors": ["blue", "green", "whitesmoke"],
"fire": ["pink", "grey", "red"]
}, {
"fcolors": ["red", "white", "yellow"],
"fire": ["black", "gray", "pink"]
}];
var fcolors = [];
for (var i = 0; i < data.length; i++) {
if (data[i].hasOwnProperty('fcolors')) {
fcolors.push(data[i].fcolors);
}
}
console.log(fcolors);
fcolors contains array
Plunker

Why are you looping JSON , when you can easily access given JSON as
me.fcolors; // It will give you ["blue", "green", "whitesmoke"]

If your array is a flat object, using the following will get the wanted value.
var jsonData = {fcolors: [...], fire: [...]};
if (jsonData.hasOwnProperty('fcolors')) {
var fcolors = jsonData.fcolors;
}
If you have multiple similar objects in the array, you could use the following to grab all the values.
var jsonData = [
{fcolors: [...], fire: [...]},
{fcolors: [...], fire: [...]},
{fcolors: [...], fire: [...]}
];
var fcolors = [];
for (var i = 0; i < jsonData.length; i++) {
var current = jsonData[i];
if (current.hasOwnProperty('fcolors')) {
fcolors.push(current.fcolors);
}
}
After which fcolors is a multidimensional array.

Related

How to dynamically create and name N data series for ApexCharts using other arrays?

I'm using ApexCharts to display data from a database, and it works perfectly fine until I have to create multiple data series. I get the data in the form of multiple arrays like so (nb: I don't get a list of fruits, it's for the sake of example)
var fruits = ["apple","apple","apple","apple","apple"]; // Name of the fruit
var dates = ["2019-04-01","2019-04-02","2019-04-03","2019-04-04","2019-04-05"];
var values = [14,9,17,5,11];
Where fruits[0] goes with dates[0] and values[0] (think of them as row in a database).
In this case I have only one data series to pass to ApexCharts and I can do it like this :
var matchedData = [];
// I create nested arrays in matchedData, each array corresponding to a tuple, like so : matched[0] = [dates[0],values[0]]
for(let i = 0; i < fruits.length; i++) {
date = new Date(dates[i]); // To transform the date string to Javascript timestamp
matchedData[i] = [date.getTime(),values[i]];
}
var options = {
chart: {
type: 'line'
},
series: [{
label: "Data",
data: matchedData
}],
xaxis: {
type: 'datetime'
},
}
var chart = new ApexCharts(document.getElementById('chart'), options);
chart.render();
But it only works when the "fruits" array contains solely one kind of fruit and not different kinds. So if my arrays are like this :
var fruits = ["apple","banana","apple","banana","strawberry"];
var dates = ["2019-04-01","2019-04-02","2019-04-03","2019-04-04","2019-04-05"];
var values = [14,9,17,5,11];
I have to dynamically create 3 arrays named each after a fruit (so in this case, "apple", "banana" and "strawberry"), each of them containing the corresponding date and value. Each array would look like this :
apple = [
["2019-04-01", 14], // I wrote the time in string for readability here but in reality it would be written in the JavaScript timestamp format
["2019-04-03", 17]
];
banana = [
["2019-04-02", 9],
["2019-04-04", 5]
];
strawberry = [
["2019-04-05",11]
];
And these data series would be passed to ApexCharts like this :
var options = {
chart: {
type: 'line'
},
series: [
{
label: "apple",
data: apple
},{
label: "banana",
data: banana
},{
label: "strawberry",
data: strawberry
}
],
xaxis: {
type: 'datetime'
},
}
var chart = new ApexCharts(document.getElementById('chart'), options);
chart.render();
My problem is the following :
I don't know how many series I will need to create until runtime, I don't know their name, and I don't know either how to pass them to ApexCharts dynamically (if there are N series, I need N {label/data} clauses).
I've got the start of a solution for dynamically creating an array for each fruit, it looks like this :
for(let i = 0; i < fruits.length; i++) {
if(fruits[i] in window) {
date = new Date(dates[i]);
window[fruits[i]].push([date.getTime(),values[i]]);
} else {
window[lines[i]] = [];
date = new Date(dates[i]);
window[lines[i]].push([date.getTime(),values[i]]);
}
}
And I can then later access each array but only if already know the different values there are in the "fruits" array.
You can use the following approach for grouping by fruit.
var fruits = ["apple","banana","apple","banana","strawberry"];
var dates = ["2019-04-01","2019-04-02","2019-04-03","2019-04-04","2019-04-05"];
var values = [14,9,17,5,11];
let result = fruits.reduce((a, f, i) => {
(a.result[f] || (a.result[f] = [])).push([a.dates[i], a.values[i]]);
return a;
}, {dates, values, result: {}}).result;
// now, you can get the apple info as follow:
console.log(JSON.stringify(result["apple"], null, 1));
console.log(JSON.stringify(result, null, 1));
.as-console-wrapper { min-height: 100%; }
I found myself. I used the window global object like I said earlier like so :
for(let i = 0; i < fruits.length; i++) {
if(!(fruits[i] in window)) {
window[fruits[i]] = [];
}
date = new Date(dates[i]);
window[fruits[i]].push([date.getTime(),values[i]]);
}
Then I made an array listing each unique name from the "fruits" array by using this function :
var fruitsName = fruits.unique();
Array.prototype.unique = function() {
return this.filter(function (value, index, self) {
return self.indexOf(value) === index;
});
}
And then I iterated on the unique names array to add each series to my chart from ApexCharts using the appendSeries() method like this :
for(let i = 0; i < fruitsName.length; i++) {
chart.appendSeries({
name: fruitsName[i],
data: window[fruitsName[i]]
});
}

Creating complex objects dynamically in javascript

Is it possible to create complex objects at runtime in javascript ? If so, what is the correct syntax ?
var food = {};
food["fruit"]["yellow"] = "banana";
food["meat"]["red"] = "steak";
food."fruit"."green" = "apple";
It's not clear what you're trying to do. If you want to build that object up all at once, then you could do something like:
var food = {
fruit: {
yellow: 'banana',
green: 'apple'
},
meat: {
red: 'steak'
}
};
If you need to piece it together one nested object at a time, then you just need to make sure that you are creating a new object to add properties to.
For example, your line:
food["fruit"]["yellow"] = "banana";
will probably fail because food.fruit does not exist.
You should do:
var food = {};
food.fruit = {};
food.fruit.yellow = 'banana';
You could write a function to add data to your object.
e.g.
function addEntry(obj, entry) {
if(entry.length < 2) return;
if(entry.length === 2) obj[entry[0]] = entry[1];
else {
if(!obj[entry[0]] || typeof obj[entry[0]] !== "object") obj[entry[0]] = {};
addEntry(obj[entry[0]], entry.slice(1));
}
}
var data = [
["fruit", "yellow", "banana"],
["meat", "red", "steak"],
["fruit", "green", "apple"]
];
var obj = {};
for(var i = 0; i < data.length; i++) {
addEntry(obj, data[i]);
}
console.log(obj);

Best Method to Merge Javascript Arrays into an Object Literal

I'm looking for a native JavaScript method to merge 2 arrays into a literal object.
Turn this:
var x = ["blue", "yellow", "red", "green", "brown", "grey", "gray", "orange"];
var y = ["james", "john", "robert", "michael", "william", "david", "richard", "wayne"];
Into this:
{
"obj" : {
"blue" : "james",
"yellow" : "john",
"red" : "robert",
"green" : "michael",
"brown" : "william",
"gray" : "david",
"grey" : "richard",
"orange" : "wayne"
}
}
You can do this with a fairly simple loop:
var result = {obj: {}};
for (var i=0; i<x.length; i++) {
result.obj[x[i]] = y[i];
}
This assumes that x and y are always the same length. If they're not, you just need to add a bit more code for checking the lengths.
var x = ["blue", "yellow", "red", "green", "brown", "grey", "gray", "orange"];
var y = ["james", "john", "robert", "michael", "william", "david", "richard", "wayne"];
function merge2array(a, b) {
var obj = {};
var l = a.length;
var i;
for (i = 0; i < l; i++) {
obj[a[i]] = b[i];
}
return obj;
}
var obj = merge2array(x, y);
console.log(obj);
This will return this object:
{
"blue" : "james",
"yellow" : "john",
"red" : "robert",
"green" : "michael",
"brown" : "william",
"gray" : "david",
"grey" : "richard",
"orange" : "wayne"
}
Then you can build your desired object:
var r = { obj: obj };
console.log(r);
There isn't a native method.
Here you can find two ways of achieving it
The first method, m1, will validate the length of your arrays, if it doesn't match it will throw an exception.
function m1(keys, values)
{
// in case the arrays have different sizes
if (keys.length != values.length)
throw new Error("Arrays are not of the same size");
var result = {};
for (var i in keys)
{
result[keys[i]] = values[i];
}
return result;
}
The second method, m2, will allow you to have more keys than values, and fill the missing values with null.
function m2(keys, values)
{
// alternative handling for different sizes
if (keys.length < values.length)
throw new Error("You can't have more values than keys");
var result = {};
for (var i in keys)
{
var val = null;
if (i < values.length)
val = values[i];
result[keys[i]] = val;
}
return result;
}
Both methods return an object, to have an object exactly as you described you will can do this:
var x = {};
x.obj = m1([1, 2, 3], ["a", "b", "c"]);
For a compact version (without validations) you can use:
function m(k,v){r={};for (i in k)r[k[i]]=v[i];return r}
Usage:
var x = { obj: m([1,2],["A","B"]) };
Change m to the desired function name.
Reference
Javascript objects
Javascript arrays
Javascript for/in loop
Javascript errors
Javascript Error object
fastest(using while--,caching length) / shortest way?
var a=['blue','yellow','red','green','brown','grey','gray','orange'],
b=['james','john','robert','michael','william','david','richard','wayne'],
c=[],d=a.length;while(d--)c[a[d]]=b[d];
var x={obj:c};
also as function (c&d are placeholder so you don't need to write var and save bytes)
the name of the function can be placed infront or after 'function'...whatever
function(a,b,c,d){c=[],d=a.length;while(d--)c[a[d]]=b[d];return c}

Setting up a variable length two-dimensional array

I have a string as follows :
Panther^Pink,Green,Yellow|Dog^Hot,Top
This string means I have 2 main blocks(separated by a '|') :
"Panther" and "Dog"
Under these two main blocks, I have, lets say "subcategories".
I wanted to create a 2-dimensional array represented (in logic) as follows :
Panther(Array 1) => Pink(Element 1),Green(Element 2), Yellow(Element 3)
Dog(Array 2) => Hot(Element 1), Top(Element 2)
Also,I want to be able to add a main block, lets say "Cat" with possible categories "Cute,Proud" to the two dimensional array
I've managed to get an Array containing "Panther^Pink,Green,Yellow" and "Dog^Hot,Top" by using JavaScript's split function.
Note that this string is received via Ajax and can be of any length, though the format shown above is always used.
----------------------------- EDIT ----------------------------
Ok, my script so far is :
$(document).ready(function(){
appFunc.setNoOfAppBlock('Panther^Pink,Green,Yellow|Dog^Hot,Top');
appFunc.alertPing();
});
var appFunc = (function(stringWithSeper) {
var result = {},
i,
categories = new Array(),
subcategories;
return {
setNoOfAppBlock: function(stringWithSeper){
categories = stringWithSeper.split("|");
for (i = 0; i < categories.length; i++) {
subcategories = categories[i].split("^");
result[subcategories[0]] = subcategories[1].split(",");
}
},
alertPing: function(){
alert(result["Panther"][1]);
}
};
})();
However, the function "alertPing" isn't "alerting" anything.What am am I doing wrong ?
To me the most logical representation of your data:
Panther^Pink,Green,Yellow|Dog^Hot,Top
Is with a JavaScript object with a property for each category, each of which is an array with the subcategories:
var data = {
Panther : ["Pink", "Green", "Yellow"],
Dog : ["Hot", "Top"]
}
You would then access that by saying, e.g., data["Dog"][1] (gives "Top").
If that format is acceptable to you then you could parse it as follows:
function parseData(data) {
var result = {},
i,
categories = data.split("|"),
subcategories;
for (i = 0; i < categories.length; i++) {
subcategories = categories[i].split("^");
result[subcategories[0]] = subcategories[1].split(",");
}
return result;
}
var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
var data = parseData(str);
Assuming you're trying to parse your data into something like this:
var result = {
Panther: ["Pink", "Green", "Yellow"],
Dog: ["Hot", "Top"]
}
you can use string.split() to break up your string into subarrays:
var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
var result = {}, temp;
var blocks = str.split("|");
for (var i = 0; i < blocks.length; i++) {
temp = blocks[i].split("^");
result[temp[0]] = temp[1].split(",");
}
Data can then be added to that data structure like this:
result["Cat"] = ["Cute", "Proud"];
Data can be read from that data structure like this:
var dogItems = result["Dog"]; // gives you an array ["Hot", "Top"]
You can use something like:
function parseInput(_input) {
var output = [];
var parts = _input.split('|');
var part;
for(var i=0; i<parts.length; i++) {
part = parts[i].split('^');
output[part[0]] = part[1].split(',');
}
return output;
}
Calling parseInput('Panther^Pink,Green,Yellow|Dog^Hot,Top'); will return:
output [
"Panther" => [ "Pink", "Green", "Yellow" ],
"Dog" => [ "Hot", "Top" ]
]
To add another item to the list, you can use:
output["Cat"] = ["Cute", "Proud"];

Coverting json array to js objects

I have a json string like this
[ {
"name":"sourabh",
"userid":"soruabhbajaj",
"id":"11",
"has_profile_image":"0" },
{
"name":"sourabh",
"userid":"sourabhbajaj",
"id":"12",
"has_profile_image":"0"
}]
Now, I want to convert this json array to the string like this so that I can access any object using its id on the entire page.
{ "11": {
"name":"sourabh",
"userid":"soruabhbajaj",
"id":"11",
"has_profile_image":"0" },
"12": {
"name":"sourabh",
"userid":"sourabhbajaj",
"id":"12",
"has_profile_image":"0"
}}
Suggest some code please. Thanx in advance
EDIT:
Will this work:
user.(function(){return id;})
And then accessing objects like this
user.id.name
I mean is this a correct way of defining object?
var data = ... the initial array
var result = {};
for (var i = 0; i < data.length; i++) {
var element = data[i];
result[element.id] = element;
};
var data = [
{"name":"sourabh", "userid":"soruabhbajaj", "id":"11", "has_profile_image":"0"},
{"name":"sourabh", "userid":"sourabhbajaj", "id":"12", "has_profile_image":"0"}
];
var newData = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
newData[item.id] = item;
}
Now newData is an object where the keys are the ids of the people and the data for each key is the person object itself. So, you can access an item like this:
var id = "11";
var name = newData[id].name;

Categories

Resources