i have this json array.
[ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ]
and here I'm trying to console log the value of every msg by doing this.
jsonArray.forEach(function(element) {
console.log(element);
console.log(element['0']);
});
output
{ '0': { msg: 'helloworld1' } }
{ '0': { msg: 'helloworld2' } }
undefined
undefined
the question is, how do i print out the values of msg keys and why is it returning undefined?
Try to parse the data again as following:
var jsonArray = [ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ]
jsonArray = JSON.parse(JSON.stringify(jsonArray));
jsonArray.forEach(function(element) {
console.log(element['0'].msg);
});
This JSON.stringify should convert the data to string then JSON.parse will convert it to JS Object.
You can use lodash for this.
var array = [ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ];
_.mapValues(array, function(array2) {
_.mapValues(array2, function(array3){
console.log(array3.msg)})
})
This will return the value in 'msg' keys. Here is the lodash documentation. loadh-map
You have no problem at all, apparently.
Check out: https://repl.it/Gh3i/0
If you click 'run' you get
helloworld1
helloworld2
The same applies if you use integers:
var jsonArray = [ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ];
jsonArray.forEach(function(element) {
console.log(element[0].msg);
});
Please find the updated code attached below
var jsonArray=[{"0":{"msg":"helloworld1"}},{"0":{"msg":"helloworld2"}}];
jsonArray.forEach(function(element) {
console.log(element[0].msg);
});
Related
How can we convert javascript __proto__ object to a json string output
this.products.forEach(function(element, index) {
productsInfo.push(productsFormItems[index].myFunction());
});
console.log(JSON.stringify(productsInfo));
myFunction() {
let result = Object.create({
ProductName: { value: this.formData.ProductName },
Address: { value: this.formData.Address }
});
return result;
}
See the sample example below:
Required json format:
"productInfo":[
{
"ProductName":"Testdata"
"Address":"TestValue"
}
]
[
{
"ProductName":"Testdata"
"Address":"TestValue"
}
]
I write parse aggregation pipeline using group and match but it doesn't work
It works in mongo compass but it rejects in parse server please suggest correct syntax
test(callback) {
let Employee = Parse.Object.extend("Employee");
var query = new Parse.Query(Employee);
var pipeline = [
[
{
'match': {
'isActive': true
}
}, {
'group': {
'objectId': null,
'total': {
'$sum': '$defaultAccNum'
}
}
}
]
]
query.aggregate(pipeline, { useMasterKey: true })
.then(function (results) {
debugger
// results contains sum of score field and stores it in results[0].total
}).catch(function (error) {
// There was an error.
});
}
}
Try:
var pipeline = [
{
'match': {
'isActive': true
}
}, {
'group': {
'objectId': null,
'total': {
'$sum': '$defaultAccNum'
}
}
}
]
I take a querystring from a URL and parse then map it so I get an object like this:
{ '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] }
Which is a const named q.
So how would the Mongoose find query look like? I tried this:
Schema.find(q, function (err, results) {
if (err) {
console.log(err);
}
else {
console.log(results);
}
});
But it gives back empty lists ([]). Upon console logging q, this prints to the console:
{ '$and': [ { length: [Object] }, { length: [Object] } ] }
--fix -- use value as a number because in your database length is cast as a number
db.collection.find({
"$and": [
{
length: {
"$gt": 2 // not '2'
}
},
{
length: {
"$lt": 55555 // not '55555'
}
}
]
})
https://mongoplayground.net/p/aJVF9QfDeKy
const q= { '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] }
// converting string key to integer
q['$and'].map(function(obj) {
for(var prop in obj.length){
if(obj.length.hasOwnProperty(prop) && obj.length[prop] !== null && !isNaN(obj.length[prop])){
obj.length[prop] = +obj.length[prop];
}
}
});
console.log(q)
Schema.find(q, function (err, results) {
if (err) {
console.log(err);
}
else {
console.log(results);
}
});
This is an example dataset:
const largeObject = {
"4249":{
"2018-07-25":[
{
"start":"2016-07-25T14:09:20.453Z",
"end":"2016-07-25T14:17:52.147Z"
}
]
},
"9939":{
"2018-07-25":[
{
"start":"2016-07-25T00:50:08.768Z",
"end":"2016-07-25T00:53:16.514Z"
}
]
},
"2149":{
"2018-07-25":[
{
"start":"2016-07-25T00:42:02.569Z",
"end":"2016-07-25T00:43:07.689Z"
}
]
},
"6929":{
"2018-07-24":[
{
"start":"2016-07-24T00:44:30.479Z",
"end":"2016-07-24T00:46:41.315Z"
}
]
},
"7930":{
"2018-07-24":[
{
"start":"2016-07-24T00:39:44.152Z",
"end":"2016-07-24T00:44:05.420Z"
}
]
},
"4796":{
"2018-07-22":[
{
"start":"2016-07-22T12:48:56.169Z",
"end":"2016-07-22T13:38:28.136Z"
}
]
}
}
I am trying to find the most efficient way to get to something like this:
const filteredObject = {
"2018-07-25": [
{
"start":"2016-07-25T14:09:20.453Z",
"end":"2016-07-25T14:17:52.147Z"
}, {
"start":"2016-07-25T00:50:08.768Z",
"end":"2016-07-25T00:53:16.514Z"
},
{
"start":"2016-07-25T00:42:02.569Z",
"end":"2016-07-25T00:43:07.689Z"
}
],
"2018-07-24": [
{
"start":"2016-07-24T00:44:30.479Z",
"end":"2016-07-24T00:46:41.315Z"
},
{
"start":"2016-07-24T00:39:44.152Z",
"end":"2016-07-24T00:44:05.420Z"
}
],
"2018-07-22": [
{
"start":"2016-07-22T12:48:56.169Z",
"end":"2016-07-22T13:38:28.136Z"
}
]
};
So far, I have done:
const filteredObject = {}
const newArr = []
for(key in largeObject){
console.log(largeObject[key])
}
And that gets rid of the random string, but still gets me this:
{ '2018-07-24':
[ { start: '2016-07-24T00:44:30.479Z',
end: '2016-07-24T00:46:41.315Z' } ] }
{ '2018-07-25':
[ { start: '2016-07-25T00:50:08.768Z',
end: '2016-07-25T00:53:16.514Z' } ] }
{ '2018-07-25':
[ { start: '2016-07-25T14:09:20.453Z',
end: '2016-07-25T14:17:52.147Z' } ] }
{ '2018-07-24':
[ { start: '2016-07-24T00:39:44.152Z',
end: '2016-07-24T00:44:05.420Z' } ] }
{ '2018-07-22':
[ { start: '2016-07-22T12:48:56.169Z',
end: '2016-07-22T13:38:28.136Z' } ] }
{ '2018-07-25':
[ { start: '2016-07-25T00:42:02.569Z',
end: '2016-07-25T00:43:07.689Z' } ] }
This is far as I've gotten. I still need to find a way to merge all the arrays with the same key values. It seems like I would need to iterate over this object, keep the date as the key, and push all of the arrays associated with that date-key into one array.
What would be the best way to handle something like this? I also want to do this as efficient as possible without having to iterate over the entire large object each time I check for the date-key and/or push the start/end object into an array of it's own.
You can start with Object.values() of your original data. This will give you an array of the values without the first level keys over which you can reduce(). Then for each of those break it into a key and value. Add the key with an array value if it's not already there and merge in the data.
const largeObject = { "4249":{ "2018-07-25":[ { "start":"2016-07-25T14:09:20.453Z","end":"2016-07-25T14:17:52.147Z"}]},"9939":{ "2018-07-25":[ { "start":"2016-07-25T00:50:08.768Z","end":"2016-07-25T00:53:16.514Z"}]},"2149":{ "2018-07-25":[ { "start":"2016-07-25T00:42:02.569Z","end":"2016-07-25T00:43:07.689Z"}]},"6929":{ "2018-07-24":[ { "start":"2016-07-24T00:44:30.479Z","end":"2016-07-24T00:46:41.315Z"}]},"7930":{ "2018-07-24":[ { "start":"2016-07-24T00:39:44.152Z","end":"2016-07-24T00:44:05.420Z"}]},"4796":{ "2018-07-22":[ { "start":"2016-07-22T12:48:56.169Z","end":"2016-07-22T13:38:28.136Z"}]}}
let filtered = Object.values(largeObject).reduce((a, c) => {
Object.entries(c).forEach(([k, v]) => {
(a[k] || (a[k] = [])).push(...v)
})
return a
},{})
console.log(filtered)
I have an array of objects like this
[ { '0': { notify_item: '1' } },
{ '1': { notify_item: '2' } },
{ '2': { notify_item: '3' } } ]
Now I want to replace '0' with some Text like 'Invoice' and the value of that '0' key with value like this { 'sms': true,email:'false' }.
And I want to replace every key with some text and their value with something like this { 'sms': true,email:'false' }
so after replacing I want something like this
[ { 'Invoice': { 'sms': true,email:'false' } },
{ 'ManualReminder': { 'sms': true,email:'false' },
{ 'AutomaticReminder': { 'sms': true,email:'false' } ]
I am not able to understand I have tried the splice method but it is not working. Please give some hint
Iterate through the array using Array.map function. In map function you can use switch statements to match the appropriate values and return the desired output.
var arr = [{
'0': { notify_item: '1' }
},
{
'1': { notify_item: '2' }
},
{
'2': { notify_item: '3' }
}];
var modifiedArr = arr.map(function(item) {
var newItem = {};
for ( var key in item) {
var newItemKey = getKey(key);
var newItemValue = getValue(item[key]);
}
newItem[newItemKey] = newItemValue;
return newItem;
});
console.log(modifiedArr);
function getKey (key) {
switch(key) {
case '0':
return 'Invoice';
case '1':
return 'ManualReminder';
case '2':
return 'AutomaticReminder';
default:
return 'default';
}
}
function getValue (value) {
switch(value.notify_item) {
case '1':
return { 'sms': true,email:'false' };
case '2':
return { 'sms': true,email:'false' };
case '3':
return { 'sms': true,email:'false' };
default:
return 'default';
}
}
[ { 'Invoice': { 'sms': true,email:'false' } },
{ 'ManualReminder': { 'sms': true,email:'false' },
{ 'AutomaticReminder': { 'sms': true,email:'false' } ]
This is a job for map.
It's also harder than it should be because the structure of your data is quite weird. Wouldn't something like { notification_type: 0, notify_item: 1 } be easier to work with?
It may not be needed to convert data, you may just get new result.
Maybe something like this will help you.
var input = [ { '0': { notify_item: '1' } },
{ '1': { notify_item: '2' } },
{ '2': { notify_item: '3' } } ];
var keyMap = {'0': 'Invoice', '1': 'ManualReminder', '2': 'AutomaticReminder'};
var result = Object.keys(input).map(function (key) {
var item = {},
value = input[key]; //{notify_item:'1'} for first iteration
//do your logic to convert {notify_item: '1' | '2' | '3'}
item[keyMap[key]] = ''; //to whatever you need
return item;
});
console.log(result);