How to filter array of arrays? - javascript

I have a JSON data. I am pushing this data to another array. The problem i am facing is, i want to filter array whose data attrs has src property. And push these array to another array. Can anyone will help me in this.I am not getting a way to do this.
My Json data is like:
DATA:
[
{
"data":{
},
"type":"image",
"attrs":{
"x":92,
"y":163,
"width":100,
"height":100,
"src":"http://localhost:63342/wodrobs/app/scripts/views/img/top.jpg",
"cursor":"move",
"opacity":1
},
"transform":"",
"id":0
},
{
"data":{
},
"type":"path",
"attrs":{
"fill":"none",
"stroke":"#000",
"stroke-dasharray":"- ",
"opacity":0.5
},
"transform":"",
"id":17
},
]

As far as I understood from your pseudo-json, you can do like this:
//your data
var a = [
{'src':"a.src"},
{'id':"someid"},
{'src':"b.src"}
];
//the result array
var result = [];
for(i=0; i<a.length;i++){
var e = a[i];
if(e.src){
result.push(e);
}
}
console.log(result);
http://jsbin.com/hujicopuca/1/edit?html,js,console,output

I think this is what you are looking for:
function HasSrcProperty(value, index, ar) {
return value.some(elem => elem.indexOf("src") > -1)
}
var result = yourJsonArray.filter(HasSrcProperty);
For more info on javascript array filter and some:
https://msdn.microsoft.com/en-us/library/ie/ff679973%28v=vs.94%29.aspx
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some

Got the answer. i was doing silly mistake.
var filterData= _.filter(jsonData, function (data) {
return data.attrs.src;
});

Related

Javascript - how to loop through dict inside a list

So I am pretty new when it comes to Javascript and it is as simple as read a json list with a value of:
{
"URL": [{
"https://testing.com/en/p/-12332423/": "999"
}, {
"https://testing.com/en/p/-123456/": "123"
},
{
"https://testing.com/en/p/-456436346/": "422"
}
]
}
What I would like to do is to have both the URL and the amount of numbers etc
"https://testing.com/en/p/-12332423/" and "999"
and I would like to for loop so it runs each "site" one by one so the first loop should be
"https://testing.com/en/p/-12332423/" and "999"
second loop should be:
"https://testing.com/en/p/-123456/" and "123"
and so on depending on whats inside the json basically.
So my question is how am I able to loop it so I can use those values for each loop?
As Adam Orlov pointed out in the coment, Object.entries() can be very useful here.
const URLobj = {
"URL": [{
"https://testing.com/en/p/-12332423/": "999"
}, {
"https://testing.com/en/p/-123456/": "123"
},
{
"https://testing.com/en/p/-456436346/": "422"
}
]
};
URLobj.URL.forEach(ob => {
console.log('ob', ob);
const entries = Object.entries(ob)[0]; // 0 just means the first key-value pair, but because each object has only one we can just use the first one
const url = entries[0];
const number = entries[1];
console.log('url', url);
console.log('number', number);
})
You mean something like this using Object.entries
const data = {
"URL": [
{"https://testing.com/en/p/-12332423/": "999"},
{"https://testing.com/en/p/-123456/": "123"},
{"https://testing.com/en/p/-456436346/": "422"}
]
}
data.URL.forEach(obj => { // loop
const [url, num] = Object.entries(obj)[0]; // grab the key and value from each entry - note the [0]
console.log("Url",url,"Number", num); // do something with them
})
let's call your object o1 for simplicity. So you can really go to town with this link - https://zellwk.com/blog/looping-through-js-objects/
or you can just use this code :
for(var i = 0; i < o1.URL.length; i++) {
//each entry
var site = Object.keys(URL[i]) [0];
var value = Object.values(URL[i]) [0];
// ... do whatever
}
don't forget each member of the array is an object (key : value) in its own right
You can extract the keys and their values into another object array using map
Then use the for loop on the newly created array. You can use this method on any object to separate their keys and values into another object array.
const data = {
"URL": [{
"https://testing.com/en/p/-12332423/": "999"
}, {
"https://testing.com/en/p/-123456/": "123"
},
{
"https://testing.com/en/p/-456436346/": "422"
}
]
}
var extracted = data.URL.map(e => ({
url: Object.keys(e)[0],
number: Object.values(e)[0]
}))
extracted.forEach((e) => console.log(e))

Combine JavaScript array with multiple sub-values (Node.js / NVD3)

I'm trying to setup a Node.js API that sends JSON data to the client for use in an NVD3 chart. The chart accepts JSON input in the following format:
[
{
"key”:”KEY NAME“,
"values":[
[
1138683600000,
14.212410956029
],
[
1141102800000,
13.973193618249
]
]
},
{
"key”:”KEY NAME“,
"values":[
[
1138683600000,
7.1590087090398
],
[
1141102800000,
7.1297210970108
]
]
}
]
However, my Node program currently outputs JSON in this format:
[
{
"key”:”SAME KEY NAME”,
"values":[
1510148301000,
34
]
},
{
"key”:”SAME KEY NAME”,
"values":[
1509626301000,
55
]
},
{
"key”:”SAME KEY NAME“,
"values":[
1509539901000,
62
]
},
{
"key”:”DIFFERENT KEY NAME“,
"values":[
1509453501000,
58
]
}
]
I want to combine any "key" indices that are the same as other ones and merge the "values" with one another in the specified format. I searched all over to find a way to do this, but each method I came across didn't account for multiple pairings within the "value" index.
Any suggestions on how I could do this?
Thanks!
You can use Array.prototype.reduce to accumulate the items from your original array into an object keyed uniquely by the item's key-value. Since this leaves you with an Object instead of an array, you can then use Object.values to spit out the array of values like your example output.
let data = [
{"key":"A", "values":[1510148301000, 34]},
{"key":"A", "values":[1509626301000, 55]},
{"key":"A", "values":[1509539901000, 62]},
{"key":"B", "values":[1509453501000, 58]},
{"key":"B", "values":[1509453501001, 57]},
];
let combined = Object.values(data.reduce((accumulator, item) => {
if (!accumulator[item.key])
accumulator[item.key] = {key: item.key, values: []};
accumulator[item.key].values.push(item.values);
return accumulator;
}, {}));
console.log(combined);
I'm not sure about what you want (merge?), but it seems to be like that:
function combine (obj) {
var combined = {}
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
if (!!combined[key]) {
combined[key] = [].concat(combined[key], obj[key].values) // everything in one
// or
// combined[key].push(obj[key].values) // everything in distinct arrays
} else {
combined[key] = obj[key].values
// or
// combined[key] = [obj[key].values] // in distinct arrays
}
}
}
return combined
}
var original=[{"key":"SAME KEY NAME","values":[1510148301000,34]},{"key":"SAME KEY NAME","values":[1509626301000,55]},{"key":"SAME KEY NAME","values":[1509539901000,62]},{"key":"DIFFERENT KEY NAME","values":[1509453501000,58]}];
var result=[];
var isAlreadyAdded=false;
original.forEach(function(outerObj){
var newObj={};
var values=[];
original.forEach(function(element) {
if(newObj["key"] !== outerObj.key){
newObj["key"]=element.key;
values=[];
values.push(element["values"]);
}else if(outerObj.key ===element.key ){
values.push(element["values"]);
}
});
newObj["values"]=values;
var count=0;
result.push(newObj);
});
var temp=[];
result=result.filter((x, i)=> {
if (temp.indexOf(x.key) < 0) {
temp.push(x.key);
return true;
}
return false;
})
console.log(result);

linq.js groupby with Json

This is my Json Object in simplified form.
var jsonObject =
[
{"City":"Monroe","Country":"USA","Latitude":47.8524,"Longitude":-121.98151},
{"City":"Austin","Country":"USA","Latitude":30.40137,"Longitude":-97.73542},
{"City":"Austin","Country":"USA","Latitude":30.32198,"Longitude":-97.70864}
]
I want to groupBy using City and get the count of records belonging to a specific city, The code that I've tried so far is
var query2 = $.Enumerable.From(jsonObject)
.GroupBy(
function(record) {return record.City},
function(record) {
return {City: record.City}
},
function(rec) {
return {City:rec}
}
).ToArray();
I'm still not able to get what i'm doing wrong here. i'm new to linq.js...any help would be appretiated, or atleast point me at right direction.
So you just wanted to get the count of cities? Try this instead:
var query = Enumerable.From(jsonObject)
.GroupBy(
"$.City",
null,
"{ City: $, Count: $$.Count() }") // $: Key, $$: Group
.ToArray();
//group the records
$.Enumerable.From(heatMapObjects)
.GroupBy(
"{ City: $.City }",
null,
function (key, g) {
var result = {
City:key.City
};
var groupResults = [];
g.ForEach(function (item) {
groupResults.push(item);
});
//push into array
groupedRecordsCollection.push(groupResults);
},
"$.City" // compare selector needed
)
.ToArray();
This solved my problem.

How to convert an object of objects to an array of objects?

I have an external file people.json. How I can convert it to a javascript array with json syntax?
this is the people.json content:
{
"1":{
"Name":"Jhon",
"Surname":"Kenneth",
"mobile":329129293,
"email":"jhon#gmail.com"
},
"2":{
"Name":"Thor",
"Surname":"zvalk",
"mobile":349229293,
"email":"thor#gmail.com"
},
"3":{
"Name":"Mila",
"Surname":"Kvuls",
"mobile":329121293,
"email":"mila#gmail.com"
}
}
I want an array with this format
var person = [
{ "name":"jhon" , "surname":"kenneth", "mobile":329129293, "email":"jhon#gmail.com"},
{ "Name":"Thor", "Surname":"zvalk", "mobile":349229293, "email":"thor#gmail.com" },
{ "Name":"Mila", "Surname":"Kvuls", "mobile":329121293, "email":"mila#gmail.com"}
];
I tried with the next code, but it doesnt worker:
var person;
$.getJSON('people.json', function (json) {
person[]= json
});
By the way, the file contacts.json is in my server.
Can use jQuery $.map()
var newArray=$.map( originalObject, function(item){
return item;
})
DEMO: http://jsfiddle.net/qmfn2/
Try like this:
$.getJSON('people.json', function (json) {
var people = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
people.push({
name: item.Name,
surname: item.Surname,
mobile: item.mobile,
email: item.email
});
}
}
// at this stage the people object will contain the desired output
});
First you will need to fetch the JSON file using an AJAX request. Then iterate through the received JSON object and add each property to an array.
function convertToArray (receivedObj) {
var array = [], key;
for (key in receivedObj) {
array.push(receivedObj[key]);
}
return array;
}
$.getJSON('people.json', function (json) {
var array = convertToArray(json);
});
Hope this helps!
Like this:
var array = $.map($.parseJSON(data), Object);
http://jsfiddle.net/mXFKL/
$.getJSON('people.json', function (json) {
var array = convertToArray(json);
});

Jquery: Iterating over nested JSON with unique key names

I have a large list of objects inside JSON like this:
var data = {
4eae1aa12efa83745d00000b: {
location: "office",
latLong: [
40.7069546, -74.0094471
],
},
4eae1aa12efa83745d000000: {
location: "home",
latLong: [
42.3584308, -71.0597732
]
}
};
Where the 4eae1aa12efa83745d00000b style key is random. How do I iterate through the JSON to print the location and latLong array of each nested JSON object?
I tried:
$.each(data, function() {
$.each(this, function() {
console.log(this.location);
});
});
but that doesn't return anything
You should look up the $.map function to translate the items in your object/array - Go for something like this:
$.map(data, function(val, i){
console.log(val.location);
console.log(val.latLong[1]);
console.log(val.latLong[2]);
})
I believe that's what you're after anyway.
Your only problem is that you don't need the inner loop.
$.each(data, function(id, value) {
console.log(value.location);
});
You are trying to loop over the properties of an object. To do this:
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
// do something with obj[prop].latLng
}
.

Categories