javascript adding object to an array - javascript

this.journeyIds = ["source", "destination"];
this.journeyDetails = [];
this.journeyIds.map((id)=>{
this.journeyDetails.push({
id: this.el("#" + id).inputValue
});
});
I want array like [{Source : "LMP"}, {Destination : "LKO"}];
i.e I want to make Id as key in object
thank you!

It seems that you want the id as key of an object. Use [] around the id
this.journeyIds = ["source", "destination"];
this.journeyDetails = [];
this.journeyIds.map((id) => {
this.journeyDetails.push({[id] :
this.el("#"+id).inputValue});
});

I don't have the function this.el() so it's an array here, you could just replace it with the function call (this.el["#"+id].inputValue => this.el("#"+id).inputValue
this.journeyIds = ["source", "destination"];
this.journeyDetails = [];
this.el = {
"#source": {inputValue: "foo"},
"#destination": {inputValue: "bar"}
}
this.journeyIds.forEach((id) => {
let temp = {};
temp[id] = this.el["#"+id].inputValue;
this.journeyDetails.push(temp);
});
console.log(this.journeyDetails)

Related

Pass array values as parameter to function and create json data

I have a scenario where I am passing an array of objects to a function in nodejs, but the same is failing with undefined error.
Here is what I have tried :
var object = issues.issues //json data
var outarr=[];
for(var key in object){
outarr.push(object[key].key)
}
console.log(outarr) // array is formed like this : ['a','b','c','d','e']
for(var i =0; i<outarr.length;i++){
jira.findIssue(outarr[i]) //here I am trying to pass the array objects into the loop one by one
.then(function(issue) {
var issue_number = issue.key
var ape = issue.fields.customfield_11442[0].value
var description = issue.fields.summary
var ice = issue.fields.customfield_15890[0].value
var vice = issue.fields.customfield_15891.value
var sor = issue.fields.labels
if (sor.indexOf("testcng") > -1) {
var val = 'yes'
} else {
var val = 'yes'
}
var obj = {};
obj['ape_n'] = ape;
obj['description_n'] = description;
obj['ice_n'] = ice;
obj['vice_n'] = vice;
obj['sor_n'] = val;
var out = {}
var key = item;
out[key] = [];
out[key].push(obj);
console.log(out)
} })
.catch(function(err) {
console.error(err);
});
});
What I am trying to achieve : I want to pass the array values as a parameter which is required by jira.findissue(bassically passing the issue number) one by one and which should again fetch the values and give a combine json output.
How can I pass this array values one by one in this function and also run jira.findissue in loop.
Any help will be great !! :-)
I have taken a look at the code in your question.
To be honest the code you wrote is messy and contains some simple syntax errors.
A good tip is to use a linter to avoid those mistakes.
More info about linters here: https://www.codereadability.com/what-are-javascript-linters/
To output all results in one array you have to define the array outside the scope of the loop.
I cleaned the code a bit up and use some es6 features. I don't know the context of the code but this is what I can make off it:
//map every value the key to outarr
let outarr = issues.issues.map( elm => elm.key);
//Output defined outside the scope of the loop
let output = [];
//looping outarr
outarr.forEach( el => {
jira.findIssue(el).then(issue => {
//creating the issue object
let obj = {
ape_n: issue.fields.customfield_11442[0].value,
description_n: issue.fields.summary,
ice_n: issue.fields.customfield_15890[0].value,
vice_n: issue.fields.customfield_15891.value,
sor_n: issue.fields.labels.indexOf("testcng") > -1 ? "yes" : "yes",
};
//pushing to the output
output[issue.key] = obj;
}).catch(err => {
console.log(err);
});
});
//ouputing the output
console.log(output);
Some more info about es6 features: https://webapplog.com/es6/

Polymer: how to do 'this.set' or 'notifyPath' on dinamically generated subproperties of JSON object?

var newUser = evt.detail.response[0];
var keys = Object.keys(evt.detail.response[0]);
var cpt = [];
keys.forEach(key => {
if (this.storedUser[key] != newUser[key]) {
this.storedUser[key] = newUser[key];
cpt.push(key);
}
});
How can I notify the change of this kind of variables?
Since I cannot do:
this.set('storedUser[key]', newUser[key]);
Nor:
this.set('storedUser'[key], newUser[key]);
Nor:
this.notifyPath('storedUser[key]');
Nor:
this.notifyPath('storedUser'[key]);
You can do (it's a string, so concat it before) :
const key = "storedUser."+key;
this.set(key, []);
from docs : https://www.polymer-project.org/2.0/docs/devguide/model-data
(same for 1.0)

Nodejs - retrieve value from nested and non-nested json

I am passing json and a key to below function to retrieve its value. The key can be like abc.cde.def nad it can also be like fgh only.
If the keys contain . then it is a nested json and values has to be retrieved accordingly which is happening correctly but if it is a plain json having no nest then it is not working. Printing the length of keysData (in case the key is like fgh) it prints 3 where it should print 1.
function getValueFromJson(jsonInput,keyInput) {
if(keyInput.includes('.')){
var keysData = keyInput.split('.');
}
else {
keysData = keyInput.toString()
}
var jsonHierarchy = jsonInput;
if(parseInt(keysData.length) === parseInt('1')){
console.log(jsonHierarchy)
console.log(keysData )
console.log(jsonHierarchy[keysData ])
jsonHierarchy = jsonHierarchy[keysData ];
}
return jsonHierarchy;
};
Can anyone please help how can I handle this ?
you dont need to check for if(keyInput.includes('.'))
just do keyInput.split('.')
//for Ex.
'abc.defg'.split('.') // result ['abc', 'defg']
'abc'.split('.') // result ['abc']
and also
if(parseInt(keysData.length) === parseInt('1'))
//can be used as
if(keysData.length === 1)
and your complete function should be
function getValueFromJson(jsonInput,keyInput) {
var keysData = keyInput.split('.');
var jsonHierarchy = jsonInput;
keysData.forEach(function(d) {
if(jsonHierarchy)
jsonHierarchy = jsonHierarchy[d];
})
return jsonHierarchy;
};
var jsonData = {
'abc': {
'def': {
'gh': 'value1'
},
'xyz': 'value2'
}
};
function getValueFromJson(jsonInput, keyInput) {
var keysData = keyInput.split('.');
var jsonHierarchy = jsonInput;
keysData.forEach(function(d) {
if (jsonHierarchy)
jsonHierarchy = jsonHierarchy[d];
})
return jsonHierarchy;
};
function get() {
var val = document.getElementById('key').value;
if (val)
console.log(getValueFromJson(jsonData, val));
};
<input id="key" />
<button onclick="get()">Get Value</button>
Convert your string to an array, then your length with show properly.
var keysData = keyInput.split('.')

Adding dynamically to multidimensional array javascript?

var oparea = [];
var mainarr_index = 0;
$("input.oparea-name").each(function(opera_key) {
var name_oparea = $(this);
oparea[mainarr_index]['maincat']['name'] = name_oparea.val(); //Add to array
$(subcats).each(function(index) {
oparea[mainarr_index]['subcat']['name'].push(name_subcat);
}
mainarr_index++;
}
The result I want:
oparea[0]['maincat']['name'] = 'name of oparea1';
oparea[0]['maincat']['subcat'] = array('name' => array('subcatname1', 'subcatname2'));
oparea[1]['maincat']['name'] = 'name of oparea2';
oparea[1]['maincat']['subcat'] = array('name' => array('subcatname1', 'subcatname2'));
//etc etc
The result I get in console is:
Uncaught TypeError: Cannot read property 'maincat' of undefined
Of course it's undefined, therefore I want to define it ;-)
How can I achieve what I want?
You can't set the property of an object if there's no object there to begin with. And you can't push onto an array if the array hasn't been created yet (I suspect you're used to PHP, which will fill these things in automatically when necessary).
And you can use .push to add the new object to the array, instead of using the oparea_index variable.
$("input.oparea-name").each(function(opera_key) {
var name_oparea = $(this);
var new_oparea = {
maincat: {
name: name_oparea.val()
},
subcat: {
name: []
}
};
$(subcats).each(function(index) {
new_oparea.subcat.name.push(name_subcat);
}
oparea.push(new_oparea);
}
var oparea = [];
$("input.oparea-name").each(function(opera_key) {
var name_oparea = $(this);
if(!oparea[mainarr_index]){
oparea[mainarr_index]={};
}
if(!oparea[mainarr_index]['maincat']){
oparea[mainarr_index]['maincat']={};
}
oparea[mainarr_index]['maincat']['name'] = name_oparea.val(); //Add to array
$(subcats).each(function(index) {
if(!oparea[mainarr_index]){
oparea[mainarr_index]={};
}
if(!oparea[mainarr_index]['subcat']){
oparea[mainarr_index]['subcat']={};
}
if(!oparea[mainarr_index]['subcat']['name']){
oparea[mainarr_index]['subcat']['name']=[];
}
oparea[mainarr_index]['subcat']['name'].push(name_subcat);
}
}

Update collection object using Underscore / Lo-dash

I have two collections of objects. I iterate trough collection A and I want when ObjectId from A matches ObjectId from B, to update that Object in collection B.
Here is what I got so far:
var exerciseIds = _(queryItems).pluck('ExerciseId').uniq().valueOf();
var item = { Exercise: null, ExerciseCategories: [] };
var exerciseAndCategories = [];
//this part works fine
_.forEach(exerciseIds, function(id) {
var temp = _.findWhere(queryItems, { 'ExerciseId': id });
item.Exercise = temp.Exercise;
exerciseAndCategories.push(item);
});
//this is problem
_.forEach(queryItems, function (i) {
_(exerciseAndCategories).where({ 'ExerciseId': i.ExerciseId }).tap(function (x) {
x.ExerciseCategories.push(i.ExerciseCategory);
}).valueOf();
});
EDIT
Link to a Fiddle
Give this a try:
var exerciseIds = _(queryItems).pluck('ExerciseId').uniq().valueOf();
var item = {
Exercise: null,
ExerciseCategories: []
};
var exerciseAndCategories = [];
//this part works fine
_.forEach(exerciseIds, function (id) {
var temp = _.findWhere(queryItems, {
'ExerciseId': id
});
var newItem = _.clone(item);
newItem.Exercise = temp.ExerciseId;
exerciseAndCategories.push(newItem);
});
//this is problem
_.forEach(queryItems, function (i) {
_(exerciseAndCategories).where({
'Exercise': i.ExerciseId
}).tap(function (x) {
return _.forEach(x, function(item) {
item.ExerciseCategories.push(i.ExerciseCategory);
});
}).valueOf();
});
// exerciseAndCategories = [{"Exercise":1,"ExerciseCategories":["biking","cardio"]},{"Exercise":2,"ExerciseCategories":["biking","cardio"]}]
Main problem was that tap returns the array, not each item, so you have to use _.forEach within that.
FIDDLE

Categories

Resources