How to join Array Values as keys to get jSON object value - javascript

I have been working on a function that loops through a JSON object recursively, and want to use each key it finds as the class value of an element to change the .text value of that element in jQuery. So, far so good, however, as I am able to get the Keys recursively as well, I'm struggling on finding a way to input all of those keys to get each json objects values:
function eachRecursive(obj, aKey)
{
aKey = aKey === null ? '' : aKey;
for (var k in obj)
{
if (typeof obj[k] == "object" && obj[k] !== null)
{
aKey += k + '_';
eachRecursive(obj[k], aKey);
}
else
{
if (obj.hasOwnProperty(k))
{
console.log(obj[k]);
if ($('.player_' + aKey + k).length)
{
var props = aKey.split('_');
props.clean("");
$('.player_' + aKey + k).text(obj[k]);
}
}
// might not even need this.
aKey = '';
}
}
}
So, text(obj[k]) isn't going to work here since the json is looping through objects inside objects recursively.
So, aKey is a string that gets used to check if the class exists (should be appending each key of the json object into it. Than should check if exists, if it does exist, should plug in the value into the .text of that element.
But what I'm sruggling here with is how to get the value from all of the keys that get plugged into an array called, props. So I will need to use each value in the array as keys for obj object to get the corresponding json value.
Can someone please help me here?
The .clean prototype added to Array just simply removes any empty values in the array. Specifically the last array index (since it splits on _).
How to pass array values into obj to get the json value?
For Example, if:
var props = ['name', 'first', 'last'];
// How to do this so we can get the value?
obj['name']['first']['last'][k]

Iterate over the props array and lookup the value in turn using bracket notation.
var value = obj;
for (var i = 0; i < props.length; i++) {
value = value[props[i]];
}
value = value[k];

Related

I have an issue with removing an object key with a for in loop

I'm using a for x in loop to check if a value is == to [] and if so remove the property using remove but it just does not seem to work.
const whosOnline = (a) => {
var obj = { online:[],
offline:[],
away:[] };
for(let i = 0; i < a.length; i++){
if(a[i].lastActivity > 10 && a[i].status == 'online'){obj.away.push(a[i].username)}
else if(a[i].status == 'offline'){obj.offline.push(a[i].username)}
else{obj.online.push(a[i].username)}
}
for(let x in obj){
console.log(obj[x])
if(obj[x] === []){delete obj[x]}}
return obj
}
you were close, however you also need to reference the array index for each object key value. Comments explaining this in the code below.
var obj = { online:[],
offline:[],
away:[] };
for(var x in obj){
if(!obj[x][0]){ // The 0 is the index inside the online array, next loop it will be the offline array and then the away array.
console.log('The array is empty');
// Do what you want to do now that it is empty
// This will continue to loop through and check the value of all the keys in the object.
}
}
console.log('done');
Good luck -
Mitch from
https://spangle.com.au
Using some debugging (simply testing if a console.log gets printed for instance) you find that your if-condition is never true.
This is because you test if an array equals a newly created empty array. This can never be the case, because objects are compared by object reference instead of value.
Instead you want to probably test to see if your array is empty by doing ‘if(obj[x].length===0)’ (or shorter: ‘if(!obj[x].length)’)

Search value in object

I have following object im not sure how to proceed.
Object image
How can I go through all objects and select the content array and search for a value x. And when the value x is in the object I need to get the object title from the object where the value was found.
Can anyone give me a hint how I can solve this problem?
you can use for...in to iterate over the object and indexOf() to check if a key exists in the array content. something like this:
function searchVal(x){
for(var key in obj){
if(obj[key].hasOwnProperty('content') && obj[key].content.includes(x))
return key;
}
}
You can use for...in to iterate the object keys, then a regular for loop to check the content array for your specific value:
function findTitle(x) {
for (var key in obj) {
for (var i = 0; i < obj[key].content.length; i++) {
if (obj[key].content[i] === x) {
return key;
}
}
}
}
let name = Object.values( obj /*your main object*/ )
.find( obj => obj.content.includes(x) )
.name;
You could find the first object in the Objects values of your main obj, that has a property content which includes x, then get the name of that object.

Javascript: Dictionary 'key' value becomes null outside for loop

I have a function which takes a list of dictionaries [{}] as an argument. It manipulates this list of dicts by adding a new key: value pair to it where value is again a list of dictionaries. This is what the function looks like, I've added comments to explain it.
function addFilesToProjects(nonUniqueArray, lists) {
var fileList = [{}]; //this will contain the list of dictionaries that I want to add as a key to the array 'nonUniqueArray'
var filesArray = []; //this was just for testing purposes because I want to access the modified version of nonUniqueArray outside the function, which I'm not able to (it shows undefined for the new key:value pair)
for (var i = 0; i < nonUniqueArray.length; i++) {
lists.forEach(function (list) {
fileNameString = JSON.stringify(list['name']).slice(2, -2);
if (fileNameString.indexOf(nonUniqueArray[i]['title']) !== -1 && fileNameString !== nonUniqueArray[i]['title']) {
fileList.push({
'name': fileNameString
});
}
});
nonUniqueArray[i]['files'] = fileList;
//this logs out the right key:value pair to the console
console.log(nonUniqueArray[i]);
filesArray.push(nonUniqueArray[i]);
while (fileList.length > 0) {
fileList.pop();
}
}
//however, now I get everything as before except the new 'files' key has empty list [] as its value :(
console.log(nonUniqueArray);
return filesArray;
}
I have no clue why is this happening, can someone help?
You seem to think that you are adding a copy of fileList into each dictionary, but in fact are adding the same fileList into each (that is, each is a reference to the same object) so that, as #vlaz points out, when you empty out the original, you are in fact emptying out what appears in each dictionary.

Find index of object in array by key

I have an array of objects like so
myobj= [{"item1" : info in here},{"item2" : info in here}, {"item3" : info in here}]
I'm trying to modify one, but I only know its key. I need to pinpoint the item1 object so I can change its value (the values are random and I don't know them, so I can't rely upon them).
If I could just get the index of the item it would be pretty easy: myobj[index].value = "newvalue".
Maybe using the index isn't the best way, so if it isn't, I'm open to other ideas.
I was thinking I could try something like
myobj.objectVar
Where objectVar is the key I'm being passed (item1, for example), however this does not work, possibly because it's a variable? Is it possible to use a variable like this maybe?
If it helps, I'm using underscore.js as well.
Your guess at a solution doesn't work because you're not accessing the individual objects, you're accessing an array of objects, each of which has a single property.
To use the data in the format you've got now, you need to iterate over the outer array until you find the object that contains the key you're after, and then modify its value.
myobj= [{"item1" : info in here},{"item2" : info in here}, {"item3" : info in here}]
function setByKey(key, value) {
myObj.forEach(function (obj) {
// only works if your object's values are truthy
if (obj[key]) {
obj[key] = value;
}
});
}
setByKey('item1', 'new value');
Of course, the far better solution is to stop using an array of single-property objects, and just use one object with multiple properties:
myobj= {"item1" : info in here, "item2" : info in here, "item3" : info in here};
Now, you can simply use myObject.item1 = "some new value" and it will work fine.
You can write a function like,
function getElementsHavingKey(key) {
var objectsHavingGivenKey = [];
//loop through all the objects in the array 'myobj'
myobj.forEach(function(individualObject) {
//you can use 'hasOwnProperty' method to find whether the provided key
// is present in the object or not
if(individualObject.hasOwnProperty(key)) {
// if the key is present, store the object having the key
// into the array (many objects may have same key in it)
objectsHavingGivenKey.push(individualObject);
}
});
// return the array containing the objects having the keys
return objectsHavingGivenKey;
}
If you only want to get the index of elements having the given key
You can do something like this,
function getIndexesOfElementsHavingKey(key) {
var objectsHavingGivenKey = [];
//loop through all the objects in the array 'myobj'
myobj.forEach(function(individualObject, index) {
//you can use 'hasOwnProperty' method to find whether the provided key
// is present in the object or not
if(individualObject.hasOwnProperty(key)) {
//push index of element which has the key
objectsHavingGivenKey.push(index);
}
});
// returns the array of element indexes which has the key
return objectsHavingGivenKey;
}
Try this code:
function changeObj( obj, key, newval )
{
for( var i=0, l=obj.length; i<j; i++)
{
if( key in obj[i] )
{
obj[i] = newval;
return;
}
}
}
var myObjArray= [{"item1" : "info in here"},{"item2" : "info in here"}, {"item3" : "info in here"}]
To find and add new value to the object inside an array:
myObjArray.forEach(function(obj) {
for(var key in obj) {
// in case you're matching key & value
if(key === "item1") {
obj[key] = "update value";
// you can even set new property as well
obj.newkey = "New value";
}
}
});
You can access objects the same using their index, even the object inside the original object.
Is this kind of what your looking for:
var otherObj = [{"oitem":"oValue"}];
var myobj= [{"item1" : otherObj},{"item2" : "2"}, {"item3" : "tesT"}];
myobj[0].item1[0].oitem = "newvalue";
alert(myobj[0].item1[0].oitem);

how to add dynamic items in a collection in javascript?

i want to add number of elements in a collection in javascript,as doing in following vb's code
Dim myList As New List(Of String)
Dim i As Integer
For i = 0 To rep_UnAssignComps.Items.Count
myList.Add(i)
Next
I want to compare this collection with a particular value.provide me syntax for comparing the value also. like
myList.Contains(val1)
Not sure what you want to store in the collection but in java-script, you have two choices to achieve collections.
First is to use arrays. For example,
var arr = []; // empty array
arr.push('A');
arr.push('B');
arr.push('C');
alert(arr.length); // alerts 3
alert(arr[1]); // alerts B (zero based indexing)
To check if any element exists or not, you have to run a loop over an array comparing element at each index.
Another method will be using java-script object as hash table. Essentially, every java-script object can have multiple properties that are essentially name-value pairs. For example,
var o = { } // empty object
o["prop1"] = "A"; // Added property named prop1 with value "A"
o["prop2"] = "B"; // Added property named prop2 with value "B"
o["prop3"] = "C"; // Added property named prop2 with value "C"
alert(o["prop1"]); // alerts A
alert(o.prop2); // alerts B - notice alternate syntax
alert(o["prop4"]); // alerts undefined - because we are accessing non-existent property
if (o["prop3"]) {
alert("prop3 exists"); // to check for some property
}
for (p in o) { // iterate all properties
alert(p); // alerts property name
alert(o[p]); // alerts property value
}
Use push method http://www.w3schools.com/jsref/jsref_push.asp
var myList = []
var i = 0;
if "rep_UnAssignComps" is an array use for loop else use for in
if (rep_UnAssignComps instanceof Array) {
for (i = 0; i < rep_UnAssignComps.length; i++){
myList.push(i);
}
}else {
for(var name in rep_UnAssignComps){
if (rep_UnAssignComps.hasOwnProperty(name)){
myList.push(i);
i++;
}
}
}
To compare use:
//Returns the first index at which a given element can be found in the array, or -1 if it is not present
myList.indexOf(val1);

Categories

Resources