Convert Object Array to an Object - javascript

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;
}

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

How can I find which index in an array contains an object whose value for a specific key is x? [duplicate]

I would like to find index in array. Positions in array are objects, and I want to filter on their properties. I know which keys I want to filter and their values. Problem is to get index of array which meets the criteria.
For now I made code to filter data and gives me back object data, but not index of array.
var data = [
{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
},
{
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}
];
var filterparams = {userid:'7', chid: 'default'};
function getIndexOfArray(thelist, props){
var pnames = _.keys(props)
return _.find(thelist, function(obj){
return _.all(pnames, function(pname){return obj[pname] == props[pname]})
})};
var check = getIndexOfArray(data, filterparams ); // Want to get '2', not key => val
Using Lo-Dash in place of underscore you can do it pretty easily with _.findIndex().
var index = _.findIndex(array, { userid: '7', chid: 'default' })
here is thefiddle hope it helps you
for(var intIndex=0;intIndex < data.length; intIndex++){
eachobj = data[intIndex];
var flag = true;
for (var k in filterparams) {
if (eachobj.hasOwnProperty(k)) {
if(eachobj[k].toString() != filterparams[k].toString()){
flag = false;
}
}
}
if(flag){
alert(intIndex);
}
}
I'm not sure, but I think that this is what you need:
var data = [{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
}, {
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}];
var filterparams = {userid:'7', chid: 'default'};
var index = data.indexOf( _.findWhere( data, filterparams ) );
I don't think you need underscore for that just regular ole js - hope this is what you are looking for
var data = [
{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
},
{
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}
];
var userid = "userid"
var filterparams = {userid:'7', chid: 'default'};
var index;
for (i=0; i < data.length; i++) {
for (prop in data[i]) {
if ((prop === userid) && (data[i]['userid'] === filterparams.userid)) {
index = i
}
}
}
alert(index);

selecting particular keys from json data

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.

remove duplicated value from array and replace it with the latest value in javascript

I have an array in JavaScript. The user enters string and the data placed in this array in the form of value and name.
if(!_.isUndefined(args[1]) && !_.isUndefined(args[2])) {
if(args[1].length !== 0 && args[2].length !== 0) {
var dataObj = {
name : args[1],
value : args[2]
};
formateArray.push({name: dataObj.name, value:dataObj.value});
How can I remove duplicated value from array and replace it with the latest value the user enters?
So when the user enters: value_1 100, value_2 200, value_1 500
I expect to see: value_1 500, value_2 200 (replace the duplicates with new data)
You can iterate your array replace the value if the name already exists.
function push(array, newVal) {
var found = false;
for (var i = 0; i < array.length && !found; i++) {
if (array[i].name === newVal.name) {
array[i].value = newVal.value;
found = true;
}
}
if (!found) {
array.push(newVal);
}
}
function printNameValue(array) {
var out = '';
for (var i = 0; i < array.length; i++) {
out += array[i].name + ' ' + array[i].value + ', ';
}
return out;
}
var myArray = [];
push(myArray, {
name: 'value_1',
value: 100
});
push(myArray, {
name: 'value_2',
value: 200
});
push(myArray, {
name: 'value_1',
value: 500
});
alert(printNameValue(myArray));
Since your values can be associated with meaningful keys, perhaps you should use an object map rather than an array to store your values. Avoiding duplicates now becomes trivial since you cannot have duplicate keys.
var valuesMap = {};
//setting value
valuesMap.value_1 = 100;
//setting another value
valuesMap.value_2 = 200;
//replacing it
valuesMap.value_1 = 500;
Otherwise it's still quite simple, but less efficient:
function add(arr, obj) {
var key = obj.name, i, len;
for (i = 0, len = arr.length; i < len; i++) {
if (arr[i].name === key) {
arr[i] = obj;
return;
}
}
arr.push(obj);
}
var values = [];
add(values, { name: 'test', value: 1 });
add(values, { name: 'test', value: 2 });
values.length; //1
Instead of the array object, i suggest you to use an object that will act like a hashtable. You can define on this way var formateArray = {};
When you want to add or edit the data, instead of using push, you can do it like this:
formateArray[dataObj.name] = {name: dataObj.name, value:dataObj.value};
If the key does not exist dataObj.name, it will be added. It the key exist, the value would set with the new value.
If you want the size of you array, you get it this way Object.keys(formateArray).length
If you want to loop on your data, you can do it this way:
for (var k in formateArray) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (formateArray.hasOwnProperty(k)) {
alert('key is: ' + k + ', value is: ' + formateArray[k].value);
}
}
Here is a jsfiddle that illustrate this.

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