selecting particular keys from json data - javascript

I have a array as:
var cols = ["ticker", "highPrice", "lowPrice","lastPrice"] // dynamic
Json data comming from backend as:
info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84}
suppose I want to select market cap then I can do info.marketCap. But I want to select only those json values which keys are equals to cols i.e. info.ticker, info.highPrice, info.lowPrice
and assign N/A to those which is undefined in json but present in cols array i.e info.lastPrice = "N/A"
Note: cols changes from time to time
Here is what I have got so far
SyScreener.fillScreenerResult = function(info) {
var cols = ["ticker", "highPrice", "lowPrice", "openPrice", "lastPrice", "currentVol", "avgVol"];
var data = [];
for(var i=0; i<info.length; i++) {
var jsonKeys = Object.keys(info[i]);
for(var j=0; j<jsonKeys.length; i++) {
if(cols.contains(jsonKey[j])) {
// TODO something like - data.push([info[i].jsonKey[j])
} else {
// TODO something like - info[i].colsValue = "N/A"
}
}
}
SyUtils.createDataTable("screener_result", data);
};

do you mean something like this:
var cols = ["ticker", "highPrice", "lowPrice","lastPrice"];
info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84};
for(var c = 0, clen = cols.length; c < clen; c++) {
if( !(cols[c] in info) ) {
console.log("N/A");
}
else {
console.log(info[cols[c]]);
}
}
Demo:: jsFiddle

I may not be reading your question correctly but from my understanding I might suggest something like this.
for (var i=0; i<cols.length; i++) {
var fieldName = cols[i];
if (!info.hasOwnProperty(fieldName)) {
info[fieldName] = 'N/A';
}
}
This simply iterates through each field name in cols and checks if it is a property of the info JSON object. If it isn't already present the loop adds the property with a value of 'N/A'.

var cols = ["ticker", "highPrice", "lowPrice","lastPrice"]
var info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84}
var output = {};
for(each in info) {
var index = cols.indexOf(each)
if(index != -1) {
output[each] = info[each];
//remove extra already checked element
cols.splice(index,1)
}
}
//append remaining keys
for(var i=0;i<cols.length;i++) {
output[cols[i]] = "N/A"
}
console.log(output)
//output Object {ticker: "AAPL", lowPrice: 42.72, highPrice: 42.84, lastPrice: "N/A"}

First thing, you nedd deserialize you JSON data.
To do this using jQuery use the function parseJson that you can find here
http://api.jquery.com/jquery.parsejson/
once you deserialized it, you can do whatever you want with this data since you manipulate it as a plain javascript array. Hope this helps.

Related

How to concatenate values of duplicate keys

When reading a csv into a javascript dictionary, how can I concatenate values of what would otherwise be duplicate keys? I've seen answers for how to do this with bash, c#, and perl, but I haven't been able to find answers for Javascript. Here's what I have:
var subjects = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
subjects[data[i].Id] = data[i].VALUE;
}
console.log(subjects);
});
This, obviously writes over existing keys. Instead, I want the key to be an array of the values. The csv basically looks like:
Id, VALUE
id1, subject1
id2, subject1
id1, subject3
And I want to output as:
{"id1": ["subject1", "subject3"], "id2": ["subject1"]...}
Just check if your output already has the key, if so you add the new value to the array. Else you create an array.
d3.csv("test.csv", function(data) {
var subjects = {};
for (var i = 0; i < data.length; i++)
{
// Check if key already exists
if(subjects.hasOwnProperty(data[i].Id)){
// push data to array
subjects[data[i].Id].push(data[i].VALUE);
}else{
// create new key and array
subjects[data[i].Id] = [data[i].VALUE];
}
}
console.log(subjects);
});
You could make it into an array and then push the content into that array
var subjects = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
//first time we see this id, turn it into an array
if(typeof subjects[data[i].Id] != "object"){
subjects[data[i].Id] = [];
}
//push content to the array
subjects[data[i].Id].push(data[i].VALUE);
}
console.log(subjects);
});
Try this inside the for loop:
typeof subjects[data[i].Id] == 'undefined' && (subjects[data[i].Id] = []);
subjects[data[i].Id].push(data[i].VALUE);
You can reduce the footprint of your code slightly if you use reduce:
var out = data.reduce((p, c) => {
const id = c.Id;
p[id] = p[id] || [];
p[id].push(c.VALUE);
return p;
}, {});
RESULT
{
"id1": [
"subject1",
"subject3"
],
"id2": [
"subject1"
]
}
DEMO

Constructing json object using javascript

I am facing issues while constructing an object using javascript. I want this:
{
"p_id": "2",
"p_name": "weblogic",
"ip_list": [
{
"ip_id": 2690
},
{
"ip_id": 2692
},
{
"ip_id": 2693
}
]
}
Below is the javascript code that I am using to get the data into the object:
var ipArray = [];
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = "2";
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push("ip_id": selectedArray[index]);
}
I am able to construct the properties for p_id and p_name but struggling to create the the ip_list. Please let me know how to get this constructed using javascript.
Code for posting to the server:
var ipArray = [];
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = 2;
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push({"ip_id": selectedArray[index]});
}
console.log (secTagJSON);
console.log (JSON.stringify(secTagJSON));
$http.post("http://server:port/api/v1/tags").
success(function(data) {
console.log (data)
});
Simply do this:
var obj = { ip_list: [] };
obj.p_name = "weblogic";
obj.p_id = "2";
for (var i = 0, j = selectedArray.length; i < j; i++)
obj.ip_list.push({ ip_id: selectedArray[i] });
Note that your ip_list is actually an array of objects. So, when you iterate over it, remember that each var item = json.ip_list[i] will return an object, that you can access its properties using: item['ip_id'].
Note that obj is an Javascript object, it is not an JSON. If you want the JSON, you can use JSON.stringify(obj). This will return your JSON (string).
Hope I've helped.
Try:
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = "2";
secTagJSON.ip_list = [];
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push({"ip_id": selectedArray[index]});
}
you forgot your {} around "ip_id": etc...
You also need to declare that ip_list is an array.
Your ip_list is an array of objects. I would guess that your script was not running as it was.
Posting to your server you should use:
$http.post('server:port/api/v1/tags', secTagJSON).sucess(...

get values in pairs from json array

Firstly, this is my json value i am getting from a php source:
[{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}]
After that, I want to get and oid value along with the corresponding cid value for example, oid=2 and cid=107 at one go, oid=4 and cid=98 at another and so on. I am trying to use jquery, ajax for this.
I have tried many answers for this, like: Javascript: Getting all existing keys in a JSON array and loop and get key/value pair for JSON array using jQuery but they don't solve my problem.
I tried this:
for (var i = 0; i < L; i++) {
var obj = res[i];
for (var j in obj) {
alert(j);
}
but all this did was to return the key name, which again did not work on being used.
So, you have an array of key/value pairs. Loop the array, at each index, log each pair:
var obj = [{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}];
for (var i = 0; i < obj.length; i++) {
console.log("PAIR " + i + ": " + obj[i].oid);
console.log("PAIR " + i + ": " + obj[i].cid);
}
Demo: http://jsfiddle.net/sTSX2/
This is an array that you have //lets call it a:
[{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}]
To get first element :
a[0] // this will give you first object i.e {"oid":"2","cid":"107"}
a[0]["oid"] // this will give you the value of the first object with the key "oid" i.e 2
and so on ...
Hope that helps.
`
Basically what you need is grouping of objects in the array with a property. Here I am giving two functions using which you can do this
// To map a property with other property in each object.
function mapProperties(array, property1, property2) {
var mapping = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
mapping[item[property1]] = mapping[item[property1]] || [];
mapping[item[property1]].push(item[property2]);
}
return mapping;
}
// To index the items based on one property.
function indexWithProperty(array, property) {
var indexing = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
indexing[item[property]] = indexing[item[property]] || [];
indexing[item[property]].push(item);
}
return indexing;
}
var data = [{
"oid": "2",
"cid": "107"
}, {
"oid": "4",
"cid": "98"
}, {
"oid": "4",
"cid": "99"
}];
var oidCidMapping = mapProperties(data, "oid", "cid");
console.log(oidCidMapping["2"]); // array of cids with oid "2"
var indexedByProperty = indexWithProperty(data, "oid");
console.log(indexedByProperty["4"]); // array of objects with cid "4"
May not be the exact solution you need, but I hope I am giving you the direction in which you have to proceed.
If you are willing to use other library you can achieve the same with underscorejs

Want to search string in the array of objects?

I want to search this employee array which is consisted of objects and i should be able to search any text like if i pass ---> search_for_string_in_array ('aaron', employees) ; it should display me 'Value exists in array' or if its the way please help me..
//here is the employeee array ...
var employees =[{
name:"jacob",
age :23,
city:"virginia",
yoe :12,
image :'a.jpg'
},
{
name:"aaron",
age :21,
city:"virginia",
yoe :12,
image :'b.jpg'
},
{
name:"johnny",
age :50,
city:"texas",
yoe :12,
image :'c.jpg'
},
{
name:"jacob",
age :12,
city:"virginia",
yoe :12,
image :'a.jpg'
}];
here is the function which performs searching functionality inside an array.
function search_for_string_in_array(search_for_string, employees)
{
for (var i=0; i < employees.length; i++)
{
if (employees[i].match(search_for_string))
{
return 'Value exists in array';
}
}
return 'Value does NOT exist in array';
}
Simply pass the value to search for and the array to the function and it will tell you whether the string exists as a part of an array value or not.
If you know the structure of the Array, you should probably just loop through it and test each value. If you don’t know the structure, you can stringify the array into JSON and regexp it (although it won’t be as safe):
function search_for_string_in_array(str, arr) {
var json = JSON.stringify(arr);
return new RegExp(':\"'+str+'\"','g').test(json);
}
just replace the line
if (employees[i].match(search_for_string))
with this:
if (employees[i].name.match(search_for_string))
Try
function search(text) {
text += '';
var i, obj;
var array = [];
for (i = 0; i < employees.length; i++) {
var obj = employees[i];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (('' + obj[key]).indexOf(text) >= 0
|| ('' + key).indexOf(text) >= 0) {
array.push(obj);
break;
}
}
}
}
return array.length > 0;
}
Demo: Fiddle1 Fiddle2

Convert Object Array to an Object

I have a returned object list: data.d[15]
and one sample of it:
data.d[3] = {
CityId: 2,
CityName: "Ankara"}
I want to convert it to one object as
cities{
1: "Istanbul",
2: "Ankara",
3: "New York"
}
And it should be generic, so I dont know the "CityId" and "CityName" field names.
what is the best method for it?
thank you all... i have send fieldnames by field object -no dependencies important for this code-, it has been resolved.
var url = this.options.url + "/" + field.values,
id = field.fieldId,
title = field.fieldTitle;
this.getJSON(url, {}, function (rData) {
var obj = {};
for (i = 0; i < rData.d.length; i++)
obj[rData.d[i][id]] = rData.d[i][title];
$("#" + parentId).html(self.getHtmlOfFormData(type, obj));
});
Maybe you need to detect which property contains the name of the city. Maybe something like this can work?
var idprop, nameprop;
for (var prop in data.d[0]) {
if (typeof data.d[0][prop] === "string") nameprop = prop;
if (typeof data.d[0][prop] === "number") idprop = prop;
}
var cities = {};
for (var i = 0; i < data.d.length; i++)
cities[data.d[i][idprop]] = data.d[i][nameprop];
Keep in mind that this works if:
data.d isn't an empty array;
there's just one string property that contains the city name;
there's just one numeric property that contains the city id.
if i understood your question, you are trying to convert some ajax return that looks like this:
data.d = [
{
cityId: someNumber1,
cityName: someName1
},
{
cityId: someNumber2,
cityName: someName2
}
];
into an object that looks like this:
cities = {
someNumber1: someName1,
someNumber2: someName2
};
a snippet like this would do the trick:
var cities = {};
for (var i = 0; i < data.d.length; i++) {
cities[data.d[i].cityId] = data.d[i].cityName;
}

Categories

Resources