find the object index using id in json - javascript

I have a json that contains many objects:
[Object, Object, Object, ... ]
Inside each object there is an object number and an id:
0: Object
id: "theObjectImLookingFor"
...
How can I find the object number (0) using the id "theObjectImLookingFor" in javascript?

Try this:
function someFunc(){
var objArr = [Object, Object, Object, ... ];
for(var i = 0; i < objArr.length; i++){
if(objArr[i].id == "theObjectImLookingFor")
return i;
}
return "No value matched";
}

This assumes there's only one property with a numeric name. This is a very strange way to store something you want to be able to look up. Why not give each object an obj_number property?
function find_object(json, str) {
for (var i = 0; i < json.length; i++) {
if (json[i].id == str) {
for (var key in json[i]) {
if (IsNumeric(key)) {
return key;
}
}
}
}
return false; // Not found
}

Related

Trying to put array as an key-value pair in objects. Not getting desired output?

I have created an insert function.
insert(obj4, ["whisky", "balentine"], ["pasta", "pesto"]);
obj4 is the item to which I intend to put those arrays pairs as key-value pairs. The first item in each array is going to be key with the second item as a value pair. I am trying to output my temp object and I am only getting [object object]. What should I do now? Is the code correct?
I have created this function: -
function insert(obj, ...pairs){
//Holds the objects temporarily
var tempObj = {};
for(let i = 1; i < arguments.length; i++){
if(arguments[i].length > 2){
console.log("Too long")
return;
} else {
tempObj[arguments[i][0]] = arguments[i][1];
}
}
//Trying to log my temp object
console.log("Test " + tempObj);
}
insert(obj4, ["whisky", "balentine"], ["pasta", "pesto"]);
To add onto what vipul patel said, if you wanted to console out the string Test and the object you could do, console.log('Test', tempObj);
You are trying to print object using string concatenation. So its printing [object object] using toString. Your code is correct though. Just print only object and you would be able to see actual Object
function insert(obj, ...pairs){
//Holds the objects temporarily
var tempObj = {};
for(let i = 1; i < arguments.length; i++){
if(arguments[i].length > 2){
console.log("Too long")
return;
} else {
tempObj[arguments[i][0]] = arguments[i][1];
}
}
//Trying to log my temp object
console.log(tempObj);
}
insert({}, ["whisky", "balentine"], ["pasta", "pesto"]);
You can also did this using reduce
function insert(obj, ...pairs){
if(pairs.length > 0){
var result = pairs.reduce(function(accumalator, currentValue){
accumalator[currentValue[0]] = currentValue[1];
return accumalator;
}, obj);
return result;
}else{
return obj;
}
}
var obj4 = {"ice":"cream"};
var result = insert(obj4, ["whisky", "balentine"], ["pasta", "pesto"]);
console.log(result);

making nested objects array and checking if the key exists in objs

I am trying to check if the keys exits in array of objects. I am getting false each time when I pass existing key to my function.
var connect_clients = [];
connect_clients.push({
'a': val
});
function lookup(name) {
for (var i = 0, len = connect_clients.length; i < len; i++) {
if (connect_clients[i].key === name)
return true;
}
return false;
}
console.log(lookup('a'));
Is there anything wrong?
connect_clients[i].key refers to the actual property named key, not the keys of the object.
For this case, you can use Object.keys to get an array of keys of an object and use Array.prototype.some to make sure that at least one of the objects has the key. For example,
function lookup(name) {
return connect_clients.some(function(client) {
return Object.keys(client).indexOf(name) !== -1;
});
}
Use Object.keys() to get keys of an object.
var val = 'val';
var connect_clients = [];
connect_clients.push({
'a': val
});
function lookup(keyName) {
var i;
for ( i = 0; i < connect_clients.length; i++) {
var keys = Object.keys(connect_clients[i]);
if(keys.indexOf(keyName) !== -1) {
return true;
}
}
return false;
}
console.log(lookup('a'));

Constructing json object using javascript

I am facing issues while constructing an object using javascript. I want this:
{
"p_id": "2",
"p_name": "weblogic",
"ip_list": [
{
"ip_id": 2690
},
{
"ip_id": 2692
},
{
"ip_id": 2693
}
]
}
Below is the javascript code that I am using to get the data into the object:
var ipArray = [];
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = "2";
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push("ip_id": selectedArray[index]);
}
I am able to construct the properties for p_id and p_name but struggling to create the the ip_list. Please let me know how to get this constructed using javascript.
Code for posting to the server:
var ipArray = [];
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = 2;
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push({"ip_id": selectedArray[index]});
}
console.log (secTagJSON);
console.log (JSON.stringify(secTagJSON));
$http.post("http://server:port/api/v1/tags").
success(function(data) {
console.log (data)
});
Simply do this:
var obj = { ip_list: [] };
obj.p_name = "weblogic";
obj.p_id = "2";
for (var i = 0, j = selectedArray.length; i < j; i++)
obj.ip_list.push({ ip_id: selectedArray[i] });
Note that your ip_list is actually an array of objects. So, when you iterate over it, remember that each var item = json.ip_list[i] will return an object, that you can access its properties using: item['ip_id'].
Note that obj is an Javascript object, it is not an JSON. If you want the JSON, you can use JSON.stringify(obj). This will return your JSON (string).
Hope I've helped.
Try:
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = "2";
secTagJSON.ip_list = [];
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push({"ip_id": selectedArray[index]});
}
you forgot your {} around "ip_id": etc...
You also need to declare that ip_list is an array.
Your ip_list is an array of objects. I would guess that your script was not running as it was.
Posting to your server you should use:
$http.post('server:port/api/v1/tags', secTagJSON).sucess(...

Want to search string in the array of objects?

I want to search this employee array which is consisted of objects and i should be able to search any text like if i pass ---> search_for_string_in_array ('aaron', employees) ; it should display me 'Value exists in array' or if its the way please help me..
//here is the employeee array ...
var employees =[{
name:"jacob",
age :23,
city:"virginia",
yoe :12,
image :'a.jpg'
},
{
name:"aaron",
age :21,
city:"virginia",
yoe :12,
image :'b.jpg'
},
{
name:"johnny",
age :50,
city:"texas",
yoe :12,
image :'c.jpg'
},
{
name:"jacob",
age :12,
city:"virginia",
yoe :12,
image :'a.jpg'
}];
here is the function which performs searching functionality inside an array.
function search_for_string_in_array(search_for_string, employees)
{
for (var i=0; i < employees.length; i++)
{
if (employees[i].match(search_for_string))
{
return 'Value exists in array';
}
}
return 'Value does NOT exist in array';
}
Simply pass the value to search for and the array to the function and it will tell you whether the string exists as a part of an array value or not.
If you know the structure of the Array, you should probably just loop through it and test each value. If you don’t know the structure, you can stringify the array into JSON and regexp it (although it won’t be as safe):
function search_for_string_in_array(str, arr) {
var json = JSON.stringify(arr);
return new RegExp(':\"'+str+'\"','g').test(json);
}
just replace the line
if (employees[i].match(search_for_string))
with this:
if (employees[i].name.match(search_for_string))
Try
function search(text) {
text += '';
var i, obj;
var array = [];
for (i = 0; i < employees.length; i++) {
var obj = employees[i];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (('' + obj[key]).indexOf(text) >= 0
|| ('' + key).indexOf(text) >= 0) {
array.push(obj);
break;
}
}
}
}
return array.length > 0;
}
Demo: Fiddle1 Fiddle2

Objects within an Array

I have multiple objects like the one below, and I was wondering what the correct syntax would be for putting them all within a single array. I'm also wondering how to correctly cycle through all of the arrays.
var verbMap = [
{
infinitive: "gehen",
thirdPres: "geht",
thirdPast: "ging",
aux: "ist",
pastPart: "gegangen",
english: "go"
},
{
infinitive: "gelingen",
thirdPres: "gelingt",
thirdPast: "gelang",
aux: "ist",
pastPart: "gelungen",
english: "succeed"
}
];
I know the correct way to cycle through that above array is:
for(v in verbMap){
for(p in verbMap[v]){
}
}
If I wanted to cycle through a larger array holding multiple arrays like verbMap, what would be the correct way to do that?
Just put the verbMap arrays in another array.
var verbMaps = [verbMap1, verbMap2...]
The key thing to understand is that your verbMap is an array of object literals. Only use
for (k in verbMap)...
for object literals.
The correct way to loop thru an array is something like
for (var i = 0; i < verbMaps.length; i++) {
var currentVerbMap = verbMaps[i];
for (var j = 0; j < currentVerbMap.length; j++) {
var currentHash = currentVerbMap[j];
for (var k in currentHash) {
console.log(k, currentHash[k];
}
}
}
The following function outputs every value from a (possibly) infinite array given as a parameter.
function printInfiniteArray(value){
if (value instanceof Array){
for(i=0;i<value.length;i++){
printInfiniteArray(value[i]);
}
} else {
console.log(value);
}
}
Edited code. Thanks jtfairbank
Your array does not contain other arrays. It contains objects. You could try this to loop though it.
for(var i = 0; i < verbMap.length; i++)
{
var obj = verbMap[i];
alert("Object #"+ i " - infinitive: " + obj.infinitive);
}
You would treat the array like any other javascript object.
var arrayOfArrays = [];
var array1 = ["cows", "horses", "chicken"];
var array2 = ["moo", "neigh", "cock-adoodle-doo"];
arrayOfArrays[0] = array1;
arrayOfArrays[1] = array2;
You can also use javascript's literal notation to create a multi-dimentional array:
var arrayOfArrays = [ ["meat", "veggies"], ["mmmm!", "yuck!"] ];
To cycle through the array of arrays, you'll need to use nested for loops, like so:
for (var i = 0; i < arrayOfArrays.length; i++) {
var myArray = arrayOfArrays[i];
for (var j = 0; j < myArray.length; j++) {
var myData = myArray[0]; // = arrayOfArrays[0][0];
}
}
DO NOT USE For...in!!!
That is not what it was made for. In javascript, For...in can have some unwanted behaviors. See Why is using "for...in" with array iteration a bad idea? for more detail.
You can use jQuery.each to cycle through an array or object, without having to check which one it is. A simple recursive function to cycle through key-value pairs in a nested structure, without knowing the exact depth:
var walk = function(o) {
$.each(o, function(key, value) {
if (typeof value == 'object') {
walk(value);
} else {
console.log(key, value);
}
});
}

Categories

Resources