Search value in object - javascript

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.

Related

Generic JSON Element Access

My colleague wrote a function to get all the keys out of a JSON object and check them against ones we're interested in. What I can't seem to search Google correctly for is how to take the variable holding the key name and use it to get the values. Obviously, idx itself is not a member of the object, but it contains the member name. How do I use idx to access obj?
$.each(JSON.parse(data[0][i]), function(idx, obj){
for(var j = 0; j < searchKeys.length; j++){
if (idx == searchKeys[j]) {
//How do I do this correctly?
injectLoc.innerHTML += panelMaker(obj.idx, idx, "green", "gears");
}
}
});
You can use it similar to how you'd access an element on an array.
var value = obj[idx];
You can access a property on an object in JavaScript like obj.prop or obj["prop"] or obj[idx] where idx === "prop".
In JSON,
Accessing elements by index --> obj[idx]
Accessing values by keys --> obj.key or obj["key"]
Note: If key has spaces use only --> obj["key"]
You can use Object.keys() to iterate keys of the object. So the function could potentially work like this:
Object.keys(obj).forEach((key, index) => {
if(index === key){
injectLoc.innerHTML += panelMaker(obj[key], index, "green", "gears");
}
})

how to insert new object in node js array if key not exist

I want to create data structure like that.
Var ans =[{"b":[1,2]},{"g":[100,2]}]
I want to create a new object within list if key not exists in list ans.
Else if key exists in one object of ans list then I want to add new values into the object of ans list
For Example:
Example 1) new data c:{2000}
then
Var ans =[{"b":[1,2]},{"g":[100,2]},{c:[2000]}]
Example 2) new data g:{50}
then
Var ans =[{"b":[1,2]},{"g":[100,2,500]},{c:[2000]}]
I am a beginner in node js, understand array, object concept, but not getting exact logic!
Thanks!
You can try following:
Logic
Filter array based on key
Check if object with mentioned key exists or not.
If yes, push value to this array.
If not, create a dummy object and push this object to original array.
Correction, when you do .push({key: value}), key will be considered as string.
Alternates
If you are using ES6, .push({ [key] : value })
Create a dummy object var o = {}. Set key and value to it o[key] = value and push this object.
Optimisations
Instead of setting value like obj[key] = value, since we will be operating on arrays, try obj[key] = [].concat(value). This will enable you to pass value as number or array of values.
Instead of checking the existence of value in .filter, try Array.isArray to check if value exists and is of type array.
Custom function
function checkAndPush(array, key, value) {
var filteredList = array.filter(function(o) {
return Array.isArray(o[key]);
});
filteredList.length > 0 ? filteredList[0][key].push(value) : array.push({
[key]: [].concat(value)
});
return array;
}
var ans =[{"b":[1,2]},{"g":[100,2]}]
console.log(checkAndPush(ans, "c", [2,3]))
console.log(checkAndPush(ans, "c", 4));
Prototype function
Array.prototype.checkAndPush = function(key, value) {
var filteredList = this.filter(function(o) {
return Array.isArray(o[key]);
});
var dummy = {}
dummy[key] = [].concat(value)
filteredList.length > 0 ? filteredList[0][key].push(value) : this.push(dummy);
// or ES6: this.push({ [key]: [].concat(value) })
return this;
}
var ans =[{"b":[1,2]},{"g":[100,2]}]
console.log(ans.checkAndPush("c", [2,3]))
console.log(ans.checkAndPush("c", 4));
If you are dealing with objects as your values
ans[key] = ans[key] || []
ans[key].push(value)
Note, this works because your values will be an array. If they could be primatives then you would use hasOwnProperty to check.
if (ans.hasOwnProperty(key)) {
// Add this to your key somehow
} else {
// initialize the key with your value
}
Node.js is nothing but a library built on javascript. You can do anything using javascript type of progmming. However push and pop method should be able to help you to deal with nodejs array.
ans[key].push(value)

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.

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

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];

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);

Categories

Resources