query javascript object in Javascript - javascript

I have a casperjs script which iterates over a list of pages and extracts data.
On the other hand I have a csv file with 2 fields 'ean' 'ref' which I parse with Papa.parse. The output is an object. I am looking for a solution to query an javascript object (the output from Papa.parse) for the 'ref' field and extract the 'ean'. I thought .filter() is what i was looking for but that can only search for a predefined value in the callback function.
function cd(element) {
return element == '123';
}
var b = c.filter(cd);
The problem hear is 1. It returns an empty array and 2. even if it would work I need to change the value with every call since I want to find the ean value for any given ref.
function cd(element,ref) {
return element == ref;
}
This is the data I need to search
"data": [
{
"ean": "654321",
"ref": "123"
},
{
"ean": "1234567",
"ref": "124"
}
]
I hope I made myself more clear. Thank you in advance

I used https://lodash.com/docs#where
Does exactly what i want
var a = _.where(array,{'ref' : 'value i am looking for'});
result is an array from where I can extract the value of the ean field.

Related

How to insert array data into json object in react js

I have a languages array. I need to insert my array data into Json Objeatc within a function.
I am a new student and I tried to do this using map. But it only inserts one data of array into a JSON object. But I need to insert all off array data one by one. But I don't know the way to that.IF anyone can help me with that it's really mean to me. Thank you.
This is how I need to be my JSON object:-
"displayNameLocalization": {
"en": "Fruits",
"fr": "des fruits",
"ja": "果物"
}
const data = {
displayNameLocalization : {},
};
const languages = ['En', 'Ta', 'Fr'];
function testFinalValue() {
displayNameLocalization.map((item) => {
data.displayName = item;
});
}
that's because you are overwritten the same variable in each loop of map, because there will be one element in data with name displayName , so in each loop you are affecting w new value to the same element that's why you input has just one value affected.
Can you afford an example of the input and the output that you want to get so I can help you with the code.

How to repalce HTML text with JSON data

Received data from api and converted into JSON format, however every time I try to change a selected element in HTML I get either undefined or Object Obejct.
I have tried JSON.parse/JSON.stringify. I have tried innerHTML, innerText, textContent. I have tried for loops.
HTML
<p id="lang">C++</p>
Javascript
let language = document.getElementById('lang');
let data = {
"book": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
}
]
};
data = JSON.stringify(data);
language.innerHTML = data.book.language;
Need C++ in paragraph tag to change to Java in data. If Jquery would make this easier I would appreciate knowing how that works as well.
Since the data model you presented has books as an array, you'll need to get that out this way
data.book[0].language
0 being the index of whatever book you want to display
data = {
"book": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
}
]
};
language.innerHTML = data.book[0].language;
This is not working as book is an array of objects, not a singular object. So you'd need to use data.book[0].language
P.S. You don't need to use JSON.stringify here, if you are receveing a JSON string from your API, you should use JSON.parse
Here is an example of the code running correctly:
https://jsfiddle.net/2et3zh7g/
From Mozilla
The JSON.stringify() method converts a JavaScript object or value to a JSON string
So it seems your code is going the opposite direction of your stated intent.
let data = {
"book": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
}
]
};
After which, data already contains an object.
data = JSON.stringify(data);
And now, data contains a string. So naturally, data.book will result in an undefined value.
If, however, you were to receive the data as actual JSON, such as
let dataJSON = '{"book":[{"id":"01","language":"Java","edition":"third","author":"Herbert Schildt"}]}';
You could then extract the language value using JSON.parse as follows:
let data = JSON.parse(dataJSON);
let bookLanguage = data.book[0].language;
language.innerText = bookLanguage;
Note the array subscript on book. Since in your example, it contains an array of objects, you need to be sure to subscript into it.

Access JSON object key/value where value is an array using underscorejs

I have a local JSON dataset (outlined below) and am trying to use the _.where method to retrieve specific values from within the dataset.
JSON File
"data": [{
"singles_ranking": [116],
"matches_lost": ["90"],
"singles_high_rank": [79],
"matches_won": ["170"],
"singles_ranking/_source": ["116"],
"year_matches_won": ["11"],
"name": ["Pfizenmaier Dinah"],
"gender": ["woman"],
"_resultNumber": 1,
},{etc},{etc}];
Currently I am trying to retrieve values from within the dataset like so:
var mappedPlayers = _.map(players,function(key,val){return key});
var filteredPlayers = _.where(mappedPlayers, {name:'Pfizenmaier Dinah'});
console.log(filteredPlayers);
This currently returns undefined. I am 90% sure that this is because the key values are stored within an array however, I am not sure how I can modify this _.where condition to actually make it return the text within the value attribute.
Any help would be greatly welcomed. Thank you for reading!
With ._where it is not possible, but you can use _.filter, like so
var where = {key: 'name', value: 'Pfizenmaier Dinah'};
var filteredPlayers = _.filter(players, function (el) {
// check if key exists in Object, check is value is Array, check if where.value exists in Array
return el[where.key] && _.isArray(el[where.key]) && _.indexOf(el[where.key], where.value) >= 0;
});
Example

Searching json array for a specific attribute

Actually I want to search an attribute's value in an json array for one of its child. Now one condition is that the attribute will not be there in all the child's of the array. This is my json array.
[{
"heading1":"heading1",
"heading2":"heading2",
"heading3":"heading3",
"heading4":"heading4",
"heading5":"heading5",
"heading6":"heading6"
},
{
"column1":65536,
"column2":"school",
"column3":"testing purpose",
"column4":"DESKTOP",
"column5":"ACTIVE",
"column6":true,
"column7":"a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
},
{
"column1":98305,
"column2":"Nikhil",
"column3":"Test",
"column4":"LAPTOP",
"column5":"ACTIVE",
"column6":true,
"column7":"a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
}]
So presently I am working with the each loop but like this
var obj = $.parseJSON(JSON.stringify(response));
$.each(obj, function () {
console.log("heading1", this['heading1']);
});
Here response comes from mserver and it is the json array
Now I want to know can I search for this attribute in the json array without using a loop in jQuery.
Based on your sample code what I understand you have is an array of objects and you want to find objects with one specific property and or value:
This will return true if the object has the property
var results= arr.filter(function(item){ return item.hasOwnProperty("column5"); });
Or you can perform additional action when you find the property:
arr.filter(function(item){
if (item.hasOwnProperty("column5")) {
return item["column5"] === 'demo 01'; //or item.column5 === 'demo 01'
}
return false;
});
This only works on IE9+ if you need this to run in older versions of IE, please follow the instructions under polyfill:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
The you can check like
var obj = $.parseJSON(response);
$.each(obj, function (index,value) {
if(typeof obj[index].heading2 !== "undefined")
{
alert(obj[index].heading2);
}
when in other object of array element not find then it returns undefined. and you can check like that.
you can check in this http://jsfiddle.net/gKRCH/
It's best to use a loop. But if the format of the JSON is regular, you could regex for the value in the response string.
I'm not recommending this method, just pointing out that it exists.
var value = "heading1";
if( (new RegExp('"' + value + '"')).test(response) ){
// Found value
};
Here, we take the required value, wrap it in quotation marks and search for it in the response.
This has several issues, such as:
It might find the pattern in a property name
If the value could contain regex special characters, they'll need escaping.
If your JSON contains values with escaped quotation marks, you could get a false positive from partial matches.
That's why it depends on you knowing the format of the data.
EDIT:
You can solve issue 2 by using this condition instead of regex. But it gives you less flexibility.
response.indexOf('"' + value + '"') !== -1
Try this,
$.each(object,function(key, value){
console.log(key);
console.log(value);
});
You can use this JS lib; DefiantJS (http://defiantjs.com). This lib extends the global object JSON with the method "search" - with which, you can perform XPath queries on JSON structures. Like the one you have exemplified.
With XPath expressions (which is standardised query language), you can find whatever you're looking for and DefiantJS will do the heavy-lifting for you - allowing your code to be neat and clean.
Here is the fiddle of this code:
http://jsfiddle.net/hbi99/q8xst/
Here is the code:
var data = [
{
"heading1": "heading1",
"heading2": "heading2",
"heading3": "heading3",
"heading4": "heading4",
"heading5": "heading5",
"heading6": "heading6"
},
{
"column1": 65536,
"column2": "school",
"column3": "testing purpose",
"column4": "DESKTOP",
"column5": "ACTIVE",
"column6": true,
"column7": "a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
},
{
"column1": 98305,
"column2": "Nikhil",
"column3": "Test",
"column4": "LAPTOP",
"column5": "ACTIVE",
"column6": true,
"column7": "a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
}
],
res = JSON.search( data, '//*[column4="DESKTOP"]' );
console.log( res[0].column2 );
// school

Attribute value turning into array unexpectedly when creating object in javascript dojo

I have below function in my dojo class:
dojo.declare("someclass", null, {
getSomeObject: function(id, name, description) {
console.log("id=", id, ", name=", name, ", description=", description);
var newObj = {
"id": id,
"name": name,
"description": description
};
console.log("newObj=", newObj);
return newObj;
}
});
This was fine until I upgraded the product I was working on. When I run the code now, somehow inside "newObj", all attribute values are turned into array - i.e. when "123" is passed as id value to function, inside newObj, "id" attribute value is ["123"].
I have tried using different ways to create object - with "new Object()", etc. Nothing seems to help. When I run the same code in the old product, it works as expected!!!
Here is an output from Google Chrome console --
id= 5962960 , name= sng2 , description= test
newObj=
Object
_RI: true
description: Array[1]
id: Array[1]
name: Array[1]
__proto__: Object
Any help???
I suppose you are using an ItemFileReadStore or ItemFileWriteStore.
Then it is absolutely normal, these stores works with arrays internally.
To get the value you should do as recommended in the doc:
store.getValue(storeItem, "property");
or if you're certain that value represented in propery, you can safely typecast by doing + ""

Categories