I am new to development, and learning angular 2 and node. Now working on a project with API integration and in the code below. I am sending all JSON data to array, I tried using JSON.stringify but did not get the desired output. And I need this kind of output:
Area = [
{ value: '3', label: 'sports' },
{ value: '4', label: 'fest' },
{ value: '5', label: 'music' }
];
My ts code is like this
var Area = [];
area=> {
console.log(departments);
area.map(function(areas) {
var array = {"value":area._id,"label":area.areaFor};
Area.push(array);
})
console.log(Area);
},
error => {
console.log(error);
});
but i am getting this output in console
label
"sports"
value
2
label
"fest"
value
3
label
"music"
value
5
You can try this, I changed area to areas inside map function.
area = [
{ value: '3', label: 'sports' },
{ value: '4', label: 'fest' },
{ value: '5', label: 'music' }
];
constructor() {
var Area = [];
Area = this.area.map(function(areas) {
return {"value":areas.value,"label":areas.label};
})
console.log(Area);
}
Related
Apologies if title is not clear.
I am using json2csv npm package to prepare csv from json object and this package allows us to add a hook to transform object before actual csv line is prepared.
I only need to manipulate two properties out of all. How can I do this effectively? My code feels too bloated.
const {
Parser: Json2csvParser,
transforms: { unwind },
} = require('json2csv');
const json2csvFields = [
{ value: 'root.filename', label: 'File Name' },
{ value: 'issue.root.priority', label: 'Priority' },
{ value: 'issue.root.url', label: 'URL' },
{ value: 'issue.root.startline', label: 'Start Line' },
{ value: 'issue.root.stopline', label: 'Stop Line' },
{ value: 'issue.root.startcolumn', label: 'Start Column' },
{ value: 'issue.root.stopcolumn', label: 'Stop Column' },
{ value: 'issue.root.issuename', label: 'Issue Name' },
{ value: 'issue.root.issuecategory', label: 'Issue Category' },
{ value: 'issue._', label: 'Issue Description' },
];
const sampleData = [
{
root: {
filename:
'/home/users/john-doe/workspace/foo-project/src/main/classes/foo.cls',
},
issue: {
root: {
priority: 1,
url: 'www.example.com',
startline: 100,
stopline: 105,
startcolumn: 20,
stopcolumn: 25,
issuename: 'blah',
issuecategory: 'Category A',
},
_: ' Fox ',
},
},
];
const json2csvOptions = {
fields: json2csvFields,
quote: '',
header: true,
transforms: [
(item) => ({
'root.filename': item.root.filename.replace(
'/home/users/john-doe/workspace/foo-project/src/main/classes/',
''
),
'issue._': `"${item.issue._.trim()}"`,
// Except for the above two, everything else doens't need any transformation.
'issue.root.priority': item.issue.root.priority,
'issue.root.url': item.issue.root.url,
'issue.root.startline': item.issue.root.startline,
'issue.root.stopline': item.issue.root.stopline,
'issue.root.startcolumn': item.issue.root.startcolumn,
'issue.root.stopcolumn': item.issue.root.stopcolumn,
'issue.root.issuename': item.issue.root.issuename,
'issue.root.issuecategory': item.issue.root.issuecategory,
}),
],
};
const json2csvParser = new Json2csvParser(json2csvOptions);
const csv = json2csvParser.parse(sampleData);
console.log(csv);
This prints below output:
File Name,Priority,URL,Start Line,Stop Line,Start Column,Stop Column,Issue Name,Issue Category,Issue Description
foo.cls,1,www.example.com,100,105,20,25,blah,Category A,"Fox"
EDIT: Updated code to a working example.
After listing the two properties with special treatment, use Object.fromEntries and Object.entries to transform all the issue.root properties to their flat structure with .s in the property names. Then that object can be spread into the returned object.
const transformsFn = ({ root, issue }) => ({
'root.filename': root.filename.replace(
'/home/users/john-doe/workspace/foo-project/src/main/classes/',
''
),
'issue._': `"${issue._.trim()}"`,
...Object.fromEntries(
Object.entries(issue.root).map(
([key, val]) => [`issue.root.${key}`, val]
)
),
});
const json2csvOptions = {
fields: json2csvFields,
quote: '',
header: true,
transforms: [transformsFn],
};
I have an array of elements and each element is super-complex because its attributes are arrays which contains other arrays as properties. I want to extract just few attributes of this element, I've tried with the forEach function but it doesn't work.
The array comes from a json file, that's why I use axios, and the elements of the array are something like this:
{
"ITEMS":[
{
"id":"0001",
"name":"foo",
"sizes":[
{
"name":"small",
"id":"9999",
"available":"no"
},
{
"name":"medium",
"id":"9998",
"available":"yes"
}
]
},
{
"id":"0002",
"name":"bar",
"sizes":[
{
"name":"small",
"id":"4444",
"available":"yes"
},
{
"name":"medium",
"id":"4443",
"available":"no"
}
]
},
...
]
}
So I want to collect the their attributes creating elements that are PUSHED in an array and that replicate this model:
this.sample = {
colour:'item.name',
size:'item.size.name[i]',
idcode:'item.id',
sizecode:'item.size.id[i]',
available:'item.size.available[i]'
}
this is my attempt (not working)
const axios = require('axios');
class IndianaJones {
constructor(){
this.sample = {
name:'',
colour:'',
size:'',
idcode:'',
sizecode:'',
available:''
},
this.newids = ["10","11","12"...]
this.freshprods = []
}
async FreshProd(){
for(this.i=0;this.i<this.newids.length;this.i++){
this.prod = await axios.get(`https://blablabla/${this.newids[this.i]}.json`)
this.ITEMS.forEach(function(item){
this.sample.idcode=item.id;
this.sample.colour=item.name;
item.sizes.forEach(function(SIZE){
this.sample.size=SIZE.name
this.sample.sizecode=SIZE.id
this.sample.available=SIZE.available
this.freshprods.push(this.sample)
})
}
)
}
return this.freshprods
}
}
(async()=>{
const indiana = new IndianaJones();
await indiana.FreshProd()
})()
Really, this is driving me up to wall, i would be SO GRATEFUL for anyone who can help me, maybe LODASH could be useful?
You are trying to flatten the structure. To so you can use Array.flatMap() (or lodash's _.flatMap() to iterate the ITEMS, map the sizes array, and return a new object for each size:
const prods = {"ITEMS":[{"id":"0001","name":"foo","sizes":[{"name":"small","id":"9999","available":"no"},{"name":"medium","id":"9998","available":"yes"}]},{"id":"0002","name":"bar","sizes":[{"name":"small","id":"4444","available":"yes"},{"name":"medium","id":"4443","available":"no"}]}]};
const freshprods = prods.ITEMS.flatMap(
({ id: idcode, name: colour, sizes }) =>
sizes.map(o => ({
colour,
size: o.name,
idcode,
sizecode: o.id,
available: o.available
}))
);
console.log(freshprods);
let prod = {
"ITEMS":[
{
"id":"0001",
"name":"foo",
"sizes":[
{
"name":"small",
"id":"9999",
"available":"no"
},
{
"name":"medium",
"id":"9998",
"available":"yes"
}
]
},
{
"id":"0002",
"name":"bar",
"sizes":[
{
"name":"small",
"id":"4444",
"available":"yes"
},
{
"name":"medium",
"id":"4443",
"available":"no"
}
]
}
]
}
let freshprods = [];
prod.ITEMS.forEach(function(item){
item.sizes.forEach(function(SIZE){
freshprods.push({
idcode: item.id,
colour: item.name,
size: SIZE.name,
sizecode: SIZE.id,
available: SIZE.available
})
})
})
console.log(freshprods);
Output
[ { idcode: '0001',
colour: 'foo',
size: 'small',
sizecode: '9999',
available: 'no' },
{ idcode: '0001',
colour: 'foo',
size: 'medium',
sizecode: '9998',
available: 'yes' },
{ idcode: '0002',
colour: 'bar',
size: 'small',
sizecode: '4444',
available: 'yes' },
{ idcode: '0002',
colour: 'bar',
size: 'medium',
sizecode: '4443',
available: 'no' } ]
I do not understand why I've got an error message, could anyone help me understand and sweat I can not do it again. I junior developer and I need your help
i have this The 'get' property does not exist on the 'any []' type.
let nodes = [];
nodes = [
{ id: 1, label: "PV Panels", color: "#3333ff" },
{ id: 2, label: "Gensets",color: "#cc00ff" },
{ id: 3, label: "Battery",color: "#ff0066" },
{ id: 4, label: "Wind Turbines",color: "#000099" }
];
net.on("selectNode", function (params) {
var selectedNode = nodes.get(params.nodes[0]);
alert("You've selected node: " + selectedNode.label);
});
With some modification the get() works.
let nodes = new vis.DataSet ([
{ id: 1, label: "PV Panels", color: "#3333ff" },
{ id: 2, label: "Gensets",color: "#cc00ff" },
{ id: 3, label: "Battery",color: "#ff0066" },
{ id: 4, label: "Wind Turbines",color: "#000099" }
]);
net.on("selectNode", function (params) {
var selectedNode = nodes.get(params.nodes[0]);
alert("You've selected node: " + selectedNode.label);
});
After this fact can you tell me how I display its information in an input.
I thought about using a getElementById.
What do you think?
The get method doesn't exist on an array. You might want to use the find method
More information can be found here: https://www.w3schools.com/jsref/jsref_find.asp
To show the result in an input field:
document.getElementById('yourInputFieldID').value = selectedNode
Assuming selectedNode variable is a string.
Considering the below data source and Listener function.
Data Source
var data = new google.visualization.DataTable(
{
cols: [{ type: 'string', label: 'Col1' },
{ type: 'number', label: 'col2' },
{ type: 'boolean', label: 'MyBoolean' }],
rows: [
{ c: [{ v: 'data1' }, { v: 1 }, {v: false}] },
{ c: [{ v: 'data2' }, { v: 2 }, {v:true}] }
]
});
Listener Function :
function ChartSelect()
{
var selectedItem = chart.getSelection()[0];
console.log(dataSource.getValue(selectedItem.row, 1));
}
I know below line will throw error
console.log(dataSource.getValue(selectedItem.row, 1));
Considering i clicked on first row, how can i read the second element of the datasource (i.e '1')?
Thank you
Got it, Its nothing more than fetching values from java script objects in object-literal-notation.
var selectedItem = chart.getSelection()[0]; // considering user clicked on first row
data["rows"][selectedItem.row]["c"][1]["v"] // will do the trick.
How can I browse a store and find the number of records which have one attribute the same?
I have tired filterBy but there you can only enter a concrete value not an attribute
Let's say I have this records:
record1{
name: 'John'
}
record2{
name'John'
}
record3{
name:'Steve'
}
Return the records with the same name
Just loop over the collection:
var seen = {};
store.each(function(rec) {
var name = rec.get('name');
if (!seen.hasOwnProperty(name)) {
seen[name] = 0;
}
++seen[name];
});
You might also be interested by Grouping:
var myStore = Ext.create('Ext.data.Store', {
groupField: 'name',
groupDir : 'DESC'
});
myStore.getGroups(); // returns:
[
{
name: 'yellow',
children: [{
name: 'John'
}, {
name: 'John'
}]
},
{
name: 'Steve',
children: [{
name: 'Steve'
}]
}
]
Then you can count how many children there is in each group.
(More details here: http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.data.Store)