I'm trying to read a sub-array from a JSON file in Polymer in JS and return the sub-array to be used in a dom-repeat. However, it tells me that the sub-array is undefined. I tried re-structuring the JSON file in various ways but no luck. I think I'm not using the right syntax somewhere.
Right now the JSON looks like this:
{
"url": "dn8",
"volpage": "DN iii 1",
"languages": [{
"pt": {
"authors": ["Laera"],
"titlelan": "Title in Portuguese"
},
"fr": {
"authors": ["Moi"],
"titlelan": "Title in French"
},
"es": {
"authors": ["Jesus"]
}
}]
}
I'm trying to get a sub-array called languageData which just hold the specific data for an input-language. The input has the correct value for the inputLanguage, like for instance "pt". My JS looks like this:
Polymer({
is: 'test-data',
properties: {
inputUrl: String,
inputLanguage: String,
inputData: {
type: Array,
notify: true,
value: function(){return []}
},
languageData: {
type: Array,
computed: '_computeLanguage(inputData,inputLanguage)'
}
},
_computeLanguage: function(inputData,inputLanguage) {
var lanarray = inputData.languages[inputLanguage];
return lanarray ? lanarray : "";
}
});
Any help is very much appreciated!
As you can see the languages property of your JSON is not an Object but and Array.
Your "Polymer code" works well, the problem is that you are trying to get the languageData as if it were an Array:
var lanarray = inputData.languages[inputLanguage];
Actually, languages contains an array of objects and you can't find your lang object in this way.
A possible solution could be:
var lanarray = inputData.languages[0][inputLanguage];
Related
I have following issue, this json is returned by api:
"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}
and I need to get names of all variables under products array, how to get them?
That values are constantly changing everyday, so I can not refer to their names
Trying console.log(res.body.menu.categories[i].products.values()); but its not worked.
Any sugesstion how can I get 10432471 and 10432481 from products? Without referring to variable names.
You are able to get that via Object.keys(res.body.menu.categories[i].products)
To get the object properties, the shortest is using Object.keys()
var obj = {"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}}
var properties = Object.keys(obj.products)
console.log(properties)
I have a Loopback moddel that looks like this:
{
"name": "string",
"elements": [
"string"
]
}
Now I want to filter if elements property conatins a certain string.
Something like this:
User.find({
filter: {
where: {elements: $scope.objects[i].id} //doesn't work, I want sth like "element contains $scope.objects[i].id
}}, function (user) {
console.log(user);
});
Warning: This solution was meant to answer the question "how do I filter a list of objects". It was accepted so I can't remove it. I don't know anything about LoopBack which has performance implications I'm not privy to. So please keep searching if you are looking for a "LoopBack" best practice.
This seems like a javascript question to me. The elements property contains an array so you can filter that array with filter().
yourModel = { // <-- Using a plain object for demo.
"name": "string",
"elements": [
"string"
]
}
matchingElements = yourModel.elements.filter(function(elm){ return elm === $scope.objects[i].id});
didMyModelHaveTheElement = matchingElments.length > 0;
I'm studying through the tutorial at http://reactivex.io/learnrx/. I'm on Exercise 19 - Reducing with an Initial Value: Sometimes when we reduce an array, we want the reduced value to be a different type than the items stored in the array. Let's say we have an array of videos and we want to reduce them to a single map where the key is the video id and the value is the video's title.
As far as the tutorial is concerned, I've solved it:
function exercise19() {
var videos = [
{
"id": 65432445,
"title": "The Chamber"
},
{
"id": 675465,
"title": "Fracture"
},
{
"id": 70111470,
"title": "Die Hard"
},
{
"id": 654356453,
"title": "Bad Boys"
}
];
return videos.reduce(function(accumulatedMap, video) {
var copyOfAccumulatedMap = Object.create(accumulatedMap);
copyOfAccumulatedMap[video.id] = video.title; // <-- My solution
return copyOfAccumulatedMap;
}, {});
} // end of overall function
To verify your solution you click, "Run." If it runs correctly then you get to move on to the next exercise. I did and it gave me the next exercise. My test suite tells me differently.
While trying to solve it, I created this test:
it("should be able to reduce to an object with id's for keys", function() {
var output = [{
"65432445": "The Chamber",
"675465": "Fracture",
"70111470": "Die Hard",
"654356453": "Bad Boys"
}];
expect(exercise19()).toEqual(output);
}); // end it
(I got the output from the tutorial.)
The problem I'm having is the test continues to fail:
Expected [ Object({ 654356453: 'Bad Boys' }) ] to equal [ Object({
65432445: 'The Chamber', 675465: 'Fracture', 70111470: 'Die Hard',
654356453: 'Bad Boys' }) ].
So it seems like it's only picking up the final property, the 'bad boys' property, in the test. I'm thinking that, with the way reduce works and Object.create, that the other properties are there, but they're on the prototype. How can I get this test to pass..?
UPDATE:
I fixed this in a pull-request. These tutorial no uses Object.assign, instead of Object.create. It is now testable. :-)
It looks like a known issue with Jasmine toEqual -- it just ignores properties from prototypes. You probably could use something like that in the test:
// ...
expect(exercise19()).toEqual(jasmine.objectContaining({
"654356453": "Bad Boys"
// rest data here
}));
Object.create creates a new object with the prototype of the object specified in the first argument - you are not copying the object at all, you are creating a new object with Object's prototype - i.e. you're doing a long winded var copyOfAccumulatedMap = {}
instead, do this
return videos.reduce(function(accumulatedMap, video) {
accumulatedMap[video.id] = video.title;
return accumulatedMap;
}, {});
I have the following sample json:
{
"camp": [
{
"name": "Name",
"data": [
{
"date": "04/08/2014",
"value": 1000
},
{
"date": "05/08/2014",
"value": 1110
}
]
}
]
}
Here, I'm able to do: model.get("camp")[0], but when I try: model.get("camp")[0].get("data"), I get the following error:
undefined is not a function
Here model is the standard backbone model which extends Backbone.Model
I'm confused what I'm doing wrong !!
You only need to call the model.get() function once. After that, you can treat the returned object just like any other javascript-object. For example, you could do this to get one of the values deep inside the object:
model.get("camp")[0].data[0].value
To achieve what you are trying to get, do this:
model.get("camp")[0].data
If you want to acces a property of your json array, you should simply do like this:
var test = json.camp.name
This is how you get your value:
obj.camp[0].data[0]
I have a JSON object that looks like this:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [ {... // contains lots objects with the data I'd like to access } ]
As noted above, I want to access the product array of objects. I can't seem to do this though. I've tried:
console.log(json['cj-api']['products'][0]['product']);
But I get typeError: Cannot read property 'products' of undefined.
What's the correct way to access the array of product (note, singular product, not products). This data is coming from an external source so I can't alter the hyphen in cj-api.
EDIT: Here's what the raw console log of json looks like:
{"cj-api":{"products":[{"$":{"total-matched":"231746","records-returned":"999","page-number":"1"},"product":[{ << lots of data in here>>
EDIT 2: To further clarify, I got this object by running JSON.stringify(result) after I put some XML into XML2js.
i have tried the following JSON structure:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [
{
"a": "a",
"b": "b",
"c": "c"
}
]
}
]
}
};
with the log statement as:
console.log(json['cj-api']['products'][0]['product']);
And result is as follows:
[Object { a="a", b="b", c="c"}]
Well your way of accessing json is absolutely correct. This is for debugging. Try
console.log(json['cj-api']);
console.log(json['cj-api']['products']);
console.log(json['cj-api']['products'][0]);
console.log(json['cj-api']['products'][0]['product']);
Which ever line returns undefined means your json is broken there.
If this doesn't work then you need to check for other similar keys. Maybe they value you are trying to find is actually undefined.
Maybe you are trying to loop. If you are then check for the condition if (JSONStructure[key]==undefined) console.log("Undefined at position ..."). That is the only way if you have valid JSON.
typeError: Cannot read property 'products' of undefined means that json exists, but json['cj-api'] is undefined. If you are sure that you are using the right variable name, I think this might be a scope issue, where you are using an other variable than you intend to. json might be the json string, instead of the array-like object. Try renaming your variable and see if you still get this problem. Otherwise the string is not automatically parsed for you and you'll have to parse it with JSON.parse( ... ).
Edit:
var json = '{ "me": "be an evil string" }';
console.log( json ); //'{ "me": "be an evil string" }'
console.log( json['me'] ); //undefined
console.log( JSON.parse( json )['me'] ); // 'be an evil string'
Since your question is missing the last
}
]
}
}
and others here changed your example and made it work, did you try to correct it?
If not then I suggest you or the dataprovider correct the structure of the reply.
I have tried below json structure
var json={
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": []
}
]
}
}
now json['cj-api']['products'][0]['product'] will work