How to I fetch some rows of particular pattern ?
var list = {
kk_list_name : "jack",
kk_list_no : "123",
kk_first_name :"Reck",
kk_first_no : "5555"
}
Here I want a map with key starting with kk_list
I tried some thing like this, which obviously didnt work.
console.log(list["kk_list_\w+"])
You can try something like this:
function filterArray( list, regex )
{
var outputArray = {};
for( var key in list )
{
if( key.match( regex ) )
{
outputArray[key] = list[key];
}
}
return outputArray;
}
var list = {
kk_list_name : "jack",
kk_list_no : "123",
kk_first_name :"Reck",
kk_first_no : "5555"
}
console.log( filterArray( list, /kk_list_\w+/ ) );
It uses a function to filter the array and make a new one with the regex-selected keys.
You can reduce the object to one with just the keys matching a specified regex using the following:
Object.prototype.reduce = function(regex) {
var newObj = {}, x;
for(x in this) if(this.hasOwnProperty(x) && (!regex || regex.test(x))) newObj[x] = this[x];
return newObj;
};
And then call it as list.reduce(/_first.*$/) => Object {kk_first_name: "Reck", kk_first_no: "5555"}
You can use the following code:
var list = {
kk_list_name : "jack",
kk_list_no : "123",
kk_first_name :"Reck",
kk_first_no : "5555"
}
var line=JSON.stringify(list);
var ar=line.match(/(kk_list[^" :]*)/g)
ar.forEach(function(val){
console.log(eval("list."+val));
});
OUTPUT
jack
123
Related
I have a JSON and I Want to separate each field of that in array part and then I want to use of each field separately and put them in separate array.
for example I have two part in my array and I want to divide the first part too room 1 and second part in room 2 .
I have to send Json to my second page with format room1 and room 2. and I do not know how can I do this
my json is like this right now :
"rooms": [
{
"adultcount": "1",
"childcount": "1,1"
},
{
"adultcount": "1",
"childcountandage": "0 "
}
]
but I want to change it like this :
"rooms": [
{
"rooms1": {
"adultcount": "1",
"childcount": "1,1"
}
},
{
"rooms2": {
"adultcount": "2",
"childcount": "10,1"
}
}
]
then I need to use them.
how can I do this with jquery ?
there is no need to change the json code I just wrote the sample the new json to define better.
here is my code :
$( document ).ready(function() {
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{ "adultcount":"1","childcountandage":"0 " }] }
var adultcount = research.rooms[0].adultcount;
var childcount = research.rooms[0].childcount;
});
Since you have an array that you want to make into an object and the property name seems to be the index inside the array, you can use a basic array.reduce:
var rooms = [
{ "adultcount":"1", "childcount":"1,1" },
{ "adultcount":"2", "childcount":"10,1" }
];
var roomsMap = rooms.reduce( function( map, room, index ) {
map[ 'room' + ( index + 1 ) ] = room;
return map;
}, {} );
var otherRoomsMap = rooms.map( function( room, index ) {
var wrapper = {};
wrapper[ 'room' + ( index + 1 ) ] = room;
return wrapper;
} );
console.log( roomsMap );
console.log( otherRoomsMap );
edit:
I have added the other example of keeping the array and just wrapping the objects isnide another object, but I have no idea what advantage that would give over the original array.
You can access your json array using loop
$.each(research, function (key, value) {
var adultcount = value.adultcount;
var childcount = value.childcount;
console.log("Adult count is:"+value.adultcount);
console.log("Child count is:"+value.childcount);
});
Try this:
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{"adultcount":"1","childcountandage":"0 " }] };
var newResearch = {"rooms": []};
research.rooms.forEach(function(r) {
newResearch.rooms.push({"room1": r[0], "room2": r[1]});
});
console.log(newResearch);
I want to use D3 v3.5.6 to convert a CSV string into a Javascript object where column names are keys and their data are in arrays.
My JS so far:
var csvString= 'date,dow,sp500,nasdaq\n1/1/16,10,15,8\n1/3/16,5,3,7\n1/5/16,12,18,12\n';
var headers = []
d3.csv.parse(csvString, function(data){
headers = d3.keys(data);
});
This fills array headers with strings of column names, but I cannot figure out how to get the data.
I would like to make an object like this:
{
"date": ["1/1/16","1/3/16","1/5/16"],
"dow": ["10","5","12"],
...
}
Is this possible with just D3?
Here is the CSV string in easy-to-read form:
date,dow,sp500,nasdaq
1/1/16,10,15,8
1/3/16,5,3,7
1/5/16,12,18,12
Well, apart from d3.csv.parse(), it seems to me that this problem has little to do with D3, and can be solved with pure JavaScript:
var csvString = 'date,dow,sp500,nasdaq\n1/1/16,10,15,8\n1/3/16,5,3,7\n1/5/16,12,18,12\n';
var data = d3.csv.parse(csvString);
var headers = d3.keys(data[0]);
var myObject = {};
headers.forEach(function(d) {
myObject[d] = [];
});
data.forEach(function(d) {
for (var key in d) {
myObject[key].push(d[key]);
}
});
console.log(myObject);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
This routine parses an array of those strings (assuming the format is consistent) and returns them as an array of strings formatted the way you want. If you want the object and not the strings, modify the function (I put a comment). You should be able to just feed this to D3.
var d3Data = splitStockStrings ( [
'date,dow,sp500,nasdaq\n1/1/16,10,15,8\n1/3/16,5,3,7\n1/5/16,12,18,12\n',
'date,dow,sp500,nasdaq\n1/1/17,10,15,8\n1/3/17,5,3,7\n1/5/17,12,18,12\n'
] );
console.log ( d3Data );
function splitStockStrings ( stockStrings ) {
var newStrings = [];
stockStrings.forEach ( function ( d ) {
var final = [];
d.split ( '\n' ).forEach ( function ( frag, i ) {
if ( i > 0 && frag.split ( ',' ) [ 0 ] ) {
final.push ( frag.split ( ',' ) [ 0 ] );
}
});
var obj = { date : final };
var json = JSON.stringify ( obj );
newStrings.push ( json );
// Or if you don't want strings,
// comment out the above and uncomment the below...
// newStrings.push ( obj );
});
return newStrings;
}
Using underscore (only cause that is what Im used to, you could use regular js map/forEach)
var csvArray = csvDataString.split(',');
var keys = _.first(csvArray);
var values = _.rest(csvArray);
var asArrayOfObjects = _.map(values, function(row) {
var mapping = {};
_.each(row, function(rowItem, i) { mapping[keys[i]] = rowItem }, {});
return mapping;
});
I am new to JS and the concepts of organising data elude me a little, trying to take data from a specific array format (as this is what I have to work with) and output it into another specific JSON format.
This is to pass data to the D3 sankey module
https://github.com/d3/d3-plugins/blob/master/sankey/sankey.js
I can't figure out is how to add the index of the node into the links, rather than the name.
Really I am just totally lost with it!
I made a fiddle here:
https://jsfiddle.net/adamdavi3s/kw3jtzx4/
Below is an example of the data and the output required
var data= [
{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var output= {
"nodes":[
{"name":"Agricultural 'waste'"},
{"name":"Bio-conversion"},
{"name":"Electricity grid"},
{"name":"Losses"},
{"name":"Liquid"}
],
"links":[
{"source":0,"target":1,"value":124.729},
{"source":1,"target":2,"value":0.597},
{"source":1,"target":3,"value":26.862},
{"source":1,"target":4,"value":280.322},
{"source":3,"target":4,"value":280.322}
]
};
Here is my code from the fiddle thusfar
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source};
var found = jQuery.inArray(node, sourceArray);
if (found < 0) {
// Element was not found, add it.
sourceArray.push(node);
}
}
console.log(sourceArray);
In javascript:
[ ] annotations are used to describe an Array, like:
var names=["John","Lisa"]
{ } Its are used to describe an Object
var person = {"name" : "John", "age" : 23}
You can use them inside one another
var people=[{"name" : "John", "age" : 23},{"name" : "Lisa", "age" : 44}]
Try this:
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
var linkArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source,};
var link= {
"source":i,
"target":data[i].target,
"value":data[i].value,
};
var found = jQuery.inArray(node, sourceArray);
if (found >= 0) {
// Element was found, remove it.
sourceArray.splice(found, 1);
linkArray.splice(found, 1);
} else {
// Element was not found, add it.
sourceArray.push(node);
linkArray.push(link);
}
}
finalArray={"nodes": sourceArray,"links": linkArray}
console.log(finalArray);
https://jsfiddle.net/9x4rdyy7/
Array.reduce() is perfect for this use case ;)
Take a look.
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var output = data.reduce(function(result, item){
for(key in search = ['source','target']) {
var value = item[search[key]];
if(! result.index.hasOwnProperty(value)){
result.index[value] = Object.keys(result.index).length;
result.nodes.push({name: value});
}
}
result.links.push({
source: result.index[item.source],
target: result.index[item.target],
value: Number(item.value)
});
return result;
}, {nodes: [], links: [], index: {}});
delete output.index;
console.log(output);
Have some issue with push the values in to the javascript array object. Please any one give me the perfect solution
Class code :
var myfuns = ( function(undefined) {
var myarr ={};
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
}
}
function _getList() {
return $.extend(true, {}, myarr);
}
return {
add : _add,
getList : _getList
}
}());
Here am calling and manage the values and keys
function setmydetails(){
var my_param = {
current_info : {
pg : '#tset',
no : 12,
name : "john",
row : 0,
},
userprofile : [],
class : [],
marks : [],
games : []
};
myfuns.add(my_param);
}
Now i got the array
myfuns.getList() // GOT proper array what i passed in my_param
Question : How to modify the existing values from any one of the Inner array from the myarr Obj
Ex: Once First array created later have to modify some from "myarr.current" = > Change current_info.row to 2222
Similar i have to add some array in to " myarr.class " etc
I would like to say try this one not tested
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
$.extend( myarr.current, arrayparam);
}
}
proper source : https://api.jquery.com/jquery.extend/
I have a problem with creating list with objects in JavaScript: the object is going to contain an Integer value and an array.
The structure will look like this (this code works):
var list = [ {
id : 1234,
dependencyList : [ {
id : 2142
}, {
id : 5313
} ]
}, {
id : 4312,
dependencyList : [ {
id : 2142
}, {
id : 5313
} ]
} ];
The problem is that I want to create this list dynamically, in other words something like this:
var list = [];
var object;
object.id=1234;
object.dependencyList = [];
object.dependencyList.push(2222);
list.push(object);
This code does not work when I try to alert(list[0].length) and it returns 0 and after using JSON.stringify(list) it only returns [[]].
Anyone know a solution for this?
list[0] is an object and not an array, which is why you're not seeing anything for length. Try:
console.log(Object.keys(list[0]).length);
Or you could even just console.log(list[0]) and check your console to ensure that it contains something.
Also, I assume you meant:
var object = {};
Because otherwise object is undefined and your script won't work. Another thing you will have to change is:
object.dependencyList.push(2222);
to:
object.dependencyList.push({id: 2222});
Object isn't defined. Do:
var object = {};
You should do list[0].dependencyList.length) also you shoud change:
object.dependencyList.push(2222);
for
object.dependencyList.push({id: 2222});
Objects are your friend.
If you need to create a lot of these things, you should probably define how they are shaped in a function. An advantage of this is that you can then create a setter for adding a dependency that hides the implementation as a push against a particular member variable.
Something like this:
function createObject( id ) {
var object = {};
object.id = id;
return object;
}
function createObjectWithDependencies( id ) {
var object = createObject( id );
object.dependencyList = [];
object.addDependency = function( dependentObject ) {
object.dependencyList.push( dependentObject );
}
return object;
}
var list = [];
var object = createObjectWithDependencies( 1234 );
object.addDependency( createObject( 2142 ) );
object.addDependency( createObject( 5313 ) );
list.push( object );
var object = createObjectWithDependencies( 4312 );
object.addDependency( createObject( 2142 ) );
object.addDependency( createObject( 5313 ) );
list.push( object );
console.log( list );