I would like to know if there is a way to get every values of "-temp" from the .json
{
"weather":{
"notes":{
"cities":[
{
"-id":"scranton",
"-temp":"17"
},
{
"-id":"paris",
"-temp":"16"
},
{
"-id":"new york",
"-temp":"18"
}
]
}
}
}
How I tried to get it with JavaScript but that didn't work and I get undefined
data.weather.notes.cities['-temp']
How can I get every value of "-temp"?
You can use map:
const temps = data.weather.notes.cities.map(city => city["-temp"]);
console.log(temps); // ["17", "16", "18"]
Of course you can always access to them individually:
const { cities } = data.weather.notes;
console.log(cities[0]["-temp"]); // "17"
Or loop all of them:
for (let city of cities) {
console.log("temperature in %s is %s°",
city["-id"], city["-temp"]
);
}
You could possibly iterate through all the cities and gather the "-temp" keys.
data.weather.notes.cities.forEach(function(element) {
for (var em in element) {
if (em == "-temp")
{
console.log(element[em])
}
}
});
#ZER0 answer is probably the best though.
var data = {
"weather":{
"notes":{
"cities":[
{
"-id":"scranton",
"-temp":"17"
},
{
"-id":"paris",
"-temp":"16"
},
{
"-id":"new york",
"-temp":"18"
}
]
}
}
};
for(var i in data.weather.notes.cities) {
let city = data.weather.notes.cities[i];
console.log(city["-temp"]); //You_ can get it here
}
You can't use JSON the same way you use jquery selectors. In your case, you need to map your array of cities.
const object = {
"weather":{
"notes":{
"cities":[
{
"-id":"scranton",
"-temp":"17"
},
{
"-id":"paris",
"-temp":"16"
},
{
"-id":"new york",
"-temp":"18"
}
]
}
}
};
const tempList = object.weather.notes.cities.map(city => city['-temp']);
//result: ["17", "16", "18"]
See map documentation for further information.
Related
Desired output will be like, I want to find last and first index. I'm having trouble in handling this. I'm not be able to get the index from this objects.
{
'13-2-2022' =>[
{
"name":"abc"
"date":"13-2-2022"
},
{
"name":"xyz"
"date":"13-2-2022"
}
]
'15-2-2022' =>[
{
"name":"azx"
"date":"15-2-2022"
},
{
"name":"qwe"
"date":"15-2-2022"
}
]
'16-2-2022' =>[
{
"name":"azx"
"date":"16-2-2022"
},
{
"name":"qwe"
"date":"16-2-2022"
}
{
"name":"qpe"
"date":"16-2-2022"
}
]
}
You can get the object keys with Object.keys function.
const keys = Object.keys(myMap);
const first = keys[0];
const last = keys[keys.length-1];
I have the following code which is changing the value of the options key in the inputType multipleChoice object the main object is called cards and I need to set the state to the newTasksIdsArray
I want the multipleChoice.options to have the newArray values so I can setthe state to them
Update: more info
I guess what I am trying to say is I need the a variable to setlocalstroage eventually to be the entireObject with the optiosn array replaced with whatever would be in newTasksIdsArray which i have generated, just not included because It't probably not neccesary
Thanks!
I need my final result to be
[
{
"inputType":"multipleChoice",
"uniId":"bzR7bpwzjMxcBEdSF",
"label":"Preferred Method of Contact",
"value":"2813348004",
"multipleChoice":{
"options":NEW ARRAY GOES HERE
}
},
...
KEEP REST OF OBJECT
]
let test = [];
cards.map((card) => {
if (card.inputType === "multipleChoice") {
//console.log(card);
card.multipleChoice.options = newTasksIdsArray;
test.push(...cards);
}
});
console.log(test);
setCards(test)
//update localstorage with test as well
This is the cards object
[
{
"inputType":"multipleChoice",
"uniId":"bzR7bpwzjMxcBEdSF",
"label":"Preferred Method of Contact",
"value":"2813348004",
"multipleChoice":{
"options":[
{
"uniId":"gJ8N6sAJrZZvCcPkp",
"label":"Cell Phone",
"checked":false
},
{
"uniId":"Ha9rmssmRkGzpRTn7",
"label":"Email",
"checked":true
}
]
}
},
{
"inputType":"shortText",
"uniId":"AkvioWe6D2ahgDCbW",
"label":"First Name:",
"value":"Kanye",
"multipleChoice":{
}
},
{
"inputType":"phoneNumber",
"uniId":"xwbBBnT2D69QJHHuL",
"label":"Cell Phone Number",
"value":"2813348004",
"multipleChoice":{
}
},
{
"inputType":"email",
"uniId":"62fDs7JtTF4MxMvww",
"label":"Work Email",
"value":"kanye#usa.gov",
"multipleChoice":{
}
},
{
"inputType":"address",
"uniId":"pKAwHmRJKCcKMz8LN",
"label":"Home Address",
"value":"123 White House Avenue",
"multipleChoice":{
}
},
{
"inputType":"dropDown",
"uniId":"K3o689k8G2ZrWEfQc",
"label":"How did you find us?",
"value":"2813348004",
"dropDown":{
"uniId":"3r9gzPXXjidq9p4fw",
"options":[
{
"uniId":"7hGYT4jv89WxFveaj",
"label":"Google"
},
{
"uniId":"J2K2W6P4BR7ZEGEao",
"label":"Referral"
}
]
},
"multipleChoice":{
}
}
]
I guess the cards state was already updated by the reaasignment of the value in the map function so this just works fine to store to localstorage
cards.map((card) => {
if (card.inputType === "multipleChoice") {
card.multipleChoice.options = newTasksIdsArray;
}
});
window.localStorage.setItem("inputs", JSON.stringify(cards)
I want to parse JSON like below
{
"nodeId":3892718504,
"root":true,
"subs":[
{
"nodeId":3892717286
},
{
"nodeId":3892716092,
"subs":[
{
"nodeId":3892715856,
"subs":[
{
"nodeId":3892718592,
"subs":[
{
"nodeId":3892717580
}
]
}
]
}
]
},
{
"nodeId":3892717497
}
]
}
Each node can have subs and those subs can have nodes that can have their own subs. all I want is an array having all nodeId, how can I parse this JSON such that an array called nodes_list is populated with all nodeId.
I can use javascript or jquery.
I'm trying the following approach to get an array of nodeId
jQuery.each(response.topology, function(i,obj) {
if(i == "nodeId") {
node_list.push(obj)
}
if(i == "subs"){
jQuery.each(i, function(key,value) {
if(i == "nodeId") {
node_list.push(obj)
}
}
}
});
I just need a little hint on how it can be in an iterative manner.
This can be done with function generators.
Perhaps not the most enjoyable approach, but I'm pretty sure the other solutions will already imply using other ways, so here is a solution using generators.
PS: Beware of browser support: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield
const input = {
"nodeId":3892718504,
"root":true,
"subs":[
{
"nodeId":3892717286
},
{
"nodeId":3892716092,
"subs":[
{
"nodeId":3892715856,
"subs":[
{
"nodeId":3892718592,
"subs":[
{
"nodeId":3892717580
}
]
}
]
}
]
},
{
"nodeId":3892717497
}
]
};
function* nodeLookup(obj) {
if (obj.nodeId) yield obj.nodeId;
if (obj.subs) for (var i = 0; i < obj.subs.length; i++) yield *nodeLookup(obj.subs[i]);
};
const node_ids = [...nodeLookup(input)];
console.log(node_ids);
Just use recursion to iterate over subs
var nodeIds = [];
if (data.nodeId) nodeIds.push(data.nodeId);
function fetchNodeIds (subs) {
if (!subs.length) return cb([]);
var abc = [];
subs.forEach(function (sub) {
abc.push(sub.nodeId);
if (sub.subs && sub.subs.length) abc = abc.concat(fetchNodeIds(sub.subs))
});
return abc;
}
nodeIds = nodeIds.concat(fetchNodeIds(data.subs));
console.log('--All nodeIds--', nodeIds)
It's straightforward to do recursively:
const gatherIds = ({nodeId, subs}, results = []) => subs
? [...results, nodeId, ...(subs .flatMap (sub => gatherIds (sub, results) ))]
: [...results, nodeId]
const response = {"nodeId": 3892718504, "root": true, "subs": [{"nodeId": 3892717286}, {"nodeId": 3892716092, "subs": [{"nodeId": 3892715856, "subs": [{"nodeId": 3892718592, "subs": [{"nodeId": 3892717580}]}]}]}, {"nodeId": 3892717497}]}
console .log (
gatherIds (response)
)
If your target environments don't support flatmap, it's easy enough to shim.
I have an Javascript object like so...
var strategies = [{
"strategy": {
"category": "war"
}
}, {
"strategy": {
"category": "farming"
}
}]
I then have an array that indicates which results I'd like back. It can be any of the following: [] OR ["war"] ["farming"] OR ["war", "farming"].
If we have the [], I want to return no results. But if ["war", "farming"] I want to return both of the results above.
How do I accomplish this with Array.prototype.filter? I saw this post, but couldn't reason through it.
strategies.filter((strategy) =>
????
)
Thanks for your help.
You can just check the value with indexOf:
var categories = ['war', 'farming'];
var filtered = strategies.filter((obj) => {
return categories.indexOf(obj.strategy.category) > -1;
});
Your object, strategy was a wrapped object, so my first line was setting it to its inner strategy and then filter as needed.
var strategies = [{
"strategy": {
"category": "war"
}
}, {
"strategy": {
"category": "farming"
}
}]
var b = ["war", "farming"];
strategies.filter(function(strategy){
strategy = strategy.strategy;
for(var i in b){
if (b[i] == strategy["category"]) {
return true;
}
}
return false;
});
Tests the input array to see if it's empty as per your requirements:
function filterObj(arr) {
return !arr.length ? arr :
strategies.filter((el) => arr.indexOf(el.strategy.category) > -1);
}
filterObj(['war', 'farming'])
DEMO
I'm trying to push a data by dynamic key
db structure:
{
"obj1":{
"array":[
{
"field1":"text1"
},
{
"field2":"text2"
}
]
},
"id":123;
},
{
"obj2":{
"array":[
{
"field1":"text1"
},
{
"field2":"text2"
}
]
},
"id":1234;
}
I'm trying to use variable as a key in map path:
var a = 'obj2';
db.collection('fooCollection').update({'id':1234},{$push:{a.array:{ "field3":"text3"}}});
if I do:
db.collection('fooCollection').update({'id':1234},{$push:{"obj2.array":{ "field3":"text3"}}});
it works, but I badly need to use dynamic key.
That can't be done with object literals. Try this:
var a = 'obj2';
var pushObj = {};
pushObj[a + '.array'] = { "field3": "text3" };
db.collection('fooCollection').update({ 'id':1234 }, { $push: pushObj });