Subsetting and editing array of objects in Javascript/Jquery - javascript

I have an array of object in Javascript that I want to subset based on key-value matches. In principle I want to access my array js_obj, change some objects where cond is true and then move on.
Let's say the array looks like this
js_obj = [{
word: "airport",
pic: "<img id='pic' src='../images/location/airport.png'/>",
cat: "location",
type: "undetermined"
}, {
word: "station",
pic: "<img id='pic' src='../images/location/station.png'/>",
cat: "location",
type: "undetermined"
}]
I now want to access js_obj where .word == "station" and of this selected object I want to change .type to "type_abc".
I was able to use each and select the object where the condition applies and change its .type as wanted, but I would like to do this within the original array. I do not simply want to filter out this object but find it, edit it, and leave the array in the modified state.
I found related posts referring to underscore.js but I think I didn't know which method to look for.
Can anybody help me with this indexing/subsetting problem?

Looping the array, checking the condition and modifying will keep it in the original array:
function modifyArrOfObjs(arr, key, condition, updateKey, updateValue) {
arr.forEach(function(obj) {
if (obj[key] == condition) {
obj[updateKey] = updateValue;
}
});
}
modifyArrOfObjs(js_obj, "word", "station", "type", "type_abc");

Related

Access items inside of an array of objects

I have a rather simple JSON file that I'm trying to access the items inside of. I had this working but for some reason it no longer works and it is making my brain hurt. Here is the JSON:
[
{
"firstItem":
{
"message": "firstItem is working",
"value": ["hello", "world"]
}
},
{
"secondItem":
{
"message": "secondItem is working",
"value": ["hello", "aliens"]
}
}
]
Note that there is an array of two objects (firstItem and secondItem) which have objects within them (message and value). I am trying to access these items like so:
// the json from above is equal to json
json.map(items => {
console.log(items.firstItem.message)
console.log(items.firstItem.value.join(", "))
console.log(items.secondItem.message)
console.log(items.secondItem.value.join(", "))
})
As always, any help would be appreciated.
Edit: I put the closing parenthesis on the joins. This was not part of my issue. I guess I'm too used to VSCode doing it for me. :)
You were missing a closing parentheses on your console.log join statements. The second and larger problem was that with map you are looping through firstItem first and then secondItem, so in the first iteration map doesn't know what secondItem is. I changed the names of each object to "item" and halved the code inside map to solve the problem:
const json = [
{
"item":
{
"message": "firstItem is working",
"value": ["hello", "world"]
}
},
{
"item":
{
"message": "secondItem is working",
"value": ["hello", "aliens"]
}
}
]
json.map(items => {
console.log(items.item.message);
console.log(items.item.value.join(", "));
})
Note that there is an array of two objects (firstItem and secondItem) which have objects within them (message and value). I am trying to access these items like so:
The example you show, shows an array containing two objects, where the first object has a property called firstItem and the second property has a property called secondItem. The properties in both the objects are objects themselves and both have two properties called message and value.
I hope that makes sense.

Javascript: Construct an object from array of objects based on matching property id's:

still quite new to higher order functions and trying to use them correctly here if possible.
I have a array of objects being returned from an api constructed like so:
[ {"gymId":3467, "halls": [{ "hallId": "25828", "instructorId": 1064,
"slotIds": [2088,2089], "sessionId":8188},
{"hallId": "25848", "instructorId": 1067, "slotIds": [2088,2089], "sessionId": 8188 }]}]
Expected result I want to achieve is to create a list of objects such as this from the array above ...
{2088: [{ "hallId":"25828", "instructorId":1064, "sessionId":8188 },
{ "hallId":"25848", "instructorId":1067, "sessionId":8188 }],
2089: [{ "hallId":"25828", "instructorId":1064, "sessionId":8188 },
{ "hallId":"25848", "instructorId":1067, "sessionId":8188 }]
}
I was thinking something along the lines of this
halls.reduce((acc, hall) => {
hall.slotIdIds.forEach(slotId => {
acc[slotId] = {
//expected object properties as above here.
};
});
return acc;
}, {}),
Problem is when I reduce in this way only one hallId is being returned and not the two matching hall ids where the slots exist.
Bit perplexed as to how to solve this one and would really appreciate any tips.

How to get the name of the array in json data using JavaScript

I have a JSON object which comes back like this from a JavaScript API call:
{
"myArray": [
{
"version": 5,
"permissionMask": 1
},
{
"version": 126,
"permissionMask": 1
}
]
}
How can I access the name of the array (i.e myArray) in JavaScript. I need to use the name of the array to determine the flow later on.
Use getOwnPropertyNames to get a list of the properties of the object in array form.
Example:
var myObj = {
"myArray": [
{
"version": 5,
"permissionMask": 1
},
{
"version": 126,
"permissionMask": 1
}
]
},
names = Object.getOwnPropertyNames(myObj);
alert(names[0]); // alerts "myArray"
Note: If the object can have more than one property, like myArray, myInt, and myOtherArray, then you will need to loop over the results of getOwnPropertyNames. You would also need to do type-testing, as in if(names[0] instanceof Array) {...} to check the property type. Based on your example in your question, I have not fleshed all of that out here.
Object.keys(data)[0]
# => "myArray"
A terminology note: This solution assumes you have a JavaScript object. You might have a JSON string, in which case this is the solution:
Object.keys(JSON.parse(data))[0]
# => "myArray"
However, "JSON object", in JavaScript, is just one - the one I used just now, that has JSON.parse and JSON.stringify methods. What you have is not a JSON object except perhaps in a trivial interpretation of the second case, where all values in JavaScript are objects, including strings.
The other answers are good if you have no control over the return format.
However, if you can, I'd recommend changing the return format to put the important values you care about as actual values instead of keys to make it clearer. For example, something like this:
result =
{
"name: "myArray",
"value": [
{
"version": 5,
"permissionMask": 1
},
{
"version": 126,
"permissionMask": 1
}
]
}
Then, it's a lot clearer to reliably access the property you care about: result.name

How to filter the json data using Underscore

I am new to Underscore. I have a json array which is pasted below. If I want to filter the below array based on developed field having "yes" as value. How can I do using Underscore.js. Currently I am iterating over the content of array and manually selecting the objects and populating in into another array. Is there a better way to do using Underscore?
{
"content": [
{
"stateName": "Karnataka",
"population": 1000000,
"developed": "yes"
},
{
"stateName": "Kerala",
"population": 1000000,
"developed": "yes"
},
{
"stateName": "Tamilnadu",
"population": 1023213213213,
"developd": "yes"
},
{
"stateName": "Bsadasd",
"population": 1023213213213,
"developed": "no"
}
]
}
Not sure if I'm missing something here but the obvious underscore function is filter:
var developedStates = _.filter(data.content, function(state){
return state.developed == 'yes';
});
You can filter an array on its properties by using _.where :
where _.where(list, properties)
Looks through each value in the list, returning an array of all the values that contain all of the
key-value pairs listed in properties.
which leads to
var filtered = _.where(data.content, {developed: "yes"});
and a demo http://jsfiddle.net/nikoshr/NExZC/
As far as I know, underscore doesn't have a way to help you with this task. You can do this without using underscore with a native Javascript method called select:
var filteredArray = originalArray.select(function(item, index) {
return item.developed == "yes"; // Include this item if it has a proper value
});
Note that the select method is only available in browsers that support EcmaScript 5 specifications, so for older browsers you will need some supporting library like es5-shim.

Using jQuery removeData() with nested data

I'm using the jQuery data() function to store data on a series of divs in a format similar to:
{
options: {
example: {
option_1: {
value: "example 1"
},
option_2: {
value: "example 2"
}
}
}
}
I can add new keys and update the data, e.g.
$("#mydiv").data('options',{'example':{} }); // the object is already created in the live version
$("#mydiv").data('options')['example']['option_3'] = { value: "example 3" };
But when I come to use removeData(), FireBug tells me that the key is undefined, e.g.
$("#mydiv").removeData('options')['example']['option_2'];
Any help appreciated!
.removeData(name) removes the previously stored data with the given name, and returns a jQuery object. In your scenario, you don't want the remove the entire options object, just a specific property of it, so you should be using delete instead:
delete $("#mydiv").data('options')['example']['option_2'];

Categories