Javascript array [duplicate] - javascript

This question already has answers here:
How and why does 'a'['toUpperCase']() in JavaScript work?
(12 answers)
Closed 9 years ago.
Im am working with some code from another developer and came across something I have not seen before. The basic functionality of the code is to look for a piece of data in an object within an object. The object format is theObj {key:Object, key:Object,...}, the data being searched for is stored in 2 variables inkey,lookfor.
$.each(theObj, function(m,n){
if(typeof(n['data'][inkey]) != "undefined" && n['data'][inkey] !== null) {
if(n['data'][inkey][lookfor] == 1){..}
}
});
What does the ['data'] do?

It is looking for a property data in the object n - n['data'] is the same as n.data

n['data'] is the same as n.data but sometime it's useful to use brackets like when you need to use a variable like n['data'][inkey].
Btw you or him should use n.data.hasOwnProperty(inkey) instead of typeof(n['data'][inkey]) != "undefined"
You could write it like that :
$.each(theObj, function(m,n){
if(n.data.hasOwnProperty(inkey) && n.data[inkey] !== null) {
if(n.data[inkey][lookfor] == 1){..}
}
});

data is the property name or key in the object. So n['data'] would return the property value for the property name data in object n.
And what you have is an Object not an Array.
Array contains list of elements with integer based index, where else Object contains list of elements with key based index.

Related

Getting an object from n object array if I have one of the keys [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 2 years ago.
I have a very complex object that looks like this:
[
{type: "type", data: {a ton more stuff}},
//with tons of these objects.
]
What I am wondering is if all 'type' keys are unique, could I get the object within the array with the given type or will I need to loop through the json array every time?? What I really need is the data, but I only know the type. This is a database schema that is not mine so unfortunately I cannot change the object.
There may be a more efficient way, but you could use Array.prototype.find():
const item = items.find(i => i.type === 'yourType');
You could also loop through once and create a Map if type is unique, using type as the key and the object as the value. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
Short answer is yes. Since it is an array of objects you need to loop through it. What you need is
const newArr = oldArr.filter(obj => (obj.type && obj.type === 'myType' && obj.data) ? obj.data : false));

How to get every value in Json by key in Javascript [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 5 years ago.
I am making a rest call to a webservice. In its body it contains a Json file with 18 pairs key, value.
I which to make separate operations on each element so i would like to:
get the different key elements. so i would have an array of the key elements.
With each of those elements, get the corresponding value by dot walking.
Here is what I have:
var obj = JSON.parse(request.body.dataString);
var myKeys = Object.keys(obj)
for (var i = 0; i < myKeys.length; i++){
var iter = myKeys[i];
gs.log(obj.iter);
}
But the gs.log returns undefined.
I have tried to make this:
gs.log(obj.myId);
and it returns the value i want, since myId is one of the elements in keys.
How can i use the elements of my keys array to get the corresponding values?
I have confirmed that hte var myKeys has all the elements of keys and the var obj contains all the json file.
You need to use the [] syntax.
var iter = myKeys[i];
gs.log(obj[iter]);
Plain obj.iter tries to get a property called literally iter. If you want to get a property based on the string value of the variable iter, you need to access the object using obj[iter].

Accessing an object from a JSON array of objects yields "Undefined" [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I'm using a Blockspring API that returns a JSON array of objects (read in from a Google Sheet). However, whenever I try to access an object from the array, an "undefined" value is returned. I have attached the code and the console log below. Does anyone have any ideas why?
blockspring.runParsed("query-public-google-spreadsheet", { "query": "SELECT A, B, C", "url":
"https://docs.google.com/spreadsheets/d/1ZYvcYf_41aghdXRSpg25TKW4Qj9p1Lpz92b1xG-9R1Q/edit?usp=sharing"},
{ "api_key": "br_50064_1fe91fe1478ef990dc8b5e9b4041c2c476670306" }, function(res){
var obj=res.params;
console.log(obj);
var temp=obj[0];
console.log(temp);
}
You need to use obj.data[0] to access the first element of an array.
Looking at your output in the console, it seems you are missing the data property of obj.
Object obj doesn't have a property with name 0 so it returns undefined.
I would need to play around with it myself but I can tell that the problem is just how you are accessing the info.
When you try to grab the data with var temp=obj[0] you are treating object like an array when is it not. I would recommend trying to grab the data using this:
//get the actual array
JSONArray theArray = obj.getJSONArray("data"); //I believe it is stored in an array called data... could be that the obj is just fine
// now get the first element:
JSONObject firstItem = theArray.getJSONObject(0);
// and so on
String name = firstItem.getString("Name"); // A
You most likely can grab it using var temp = obj.data[0];

Javascript list contains a string [duplicate]

This question already has answers here:
Determine whether an array contains a value [duplicate]
(18 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Does anyone know of a way to check if a list contains a string without using indexOf? In my array some strings can contains parts of others, so indexOf will produce false positives.
As an example, how would I determine if "component" is in the array below?
["component.part", "random-component", "prefix-component-name", "component"]
Update:
It seems like my use of false positive was misleading. I meant that it would say that component was in there 4 times, when I want to match the string by itself.
ie. It should return false when checking for the presence of "component" in the below array.
["component.part", "random-component", "prefix-component-name"]
Use the Array.find API.
Example:
"use strict";
let items = ["component.part", "random-component", "prefix-component-name", "component"];
let found = items.find(item => { return item === "component.part" } );
if (found) {
console.log("Item exists.");
}
For more usage example.
See:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find
One way is to use .find() to get the string you want from the Array.
Try using $.inArray() method.
var list=["component.part", "random-component", "prefix-component-name", "component"];
if($.inArray(" component",list) != -1){
console.log("Item found");
}
Does anyone know of a way to check if a list contains a string without using indexOf? In my array some strings can contains parts of others, so indexOf will produce false positives.
false positives? Array.prototype.indexOf and Array.prototype.includes both use strict equality which makes that impossible here.
IndexOf won't give you false positive. It will give you 3. If you want to find all elements that has "otherstuff componenet" you can loop through your array and check with String.includes()
Here is a beginner friendly solution.
var arr = ["component.part", "random-component",
"prefix-component-name", "component", "asdf"];
console.log(arr.indexOf('component')); // give u 3
for (var i = 0; i < arr.length; i++){
if (arr[i].includes('component')){
console.log(arr[i]);
}
}

Compare 2 JSON objects [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Object comparison in JavaScript
Is there any method that takes in 2 JSON objects and compares the 2 to see if any data has changed?
Edit
After reviewing the comments, some clarification is needed.
A JSON object is defined as
"an unordered set of name/value pairs.
An object begins with { (left brace)
and ends with } (right brace). Each
name is followed by : (colon) and the
name/value pairs are separated by ,
(comma)." -- json.org
My goal is to be able to compare 2 JSON object literals, simply put.
I am not a javascript guru so if, in javascript, these are object literals, then I suppose that's what I should call them.
I believe what I am looking for is a method capable of:
Deep recursion to find a unique name/value pair
Determine the length of both object literals, and compare the name/value pairs to see if a discrepancy exists in either.
Simply parsing the JSON and comparing the two objects is not enough because
it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...

Categories

Resources