My data is currently stored in this format:
{
"Site1":{
"week":[
{
"access":1
},
{
"access":8
}
]
},
"Site2":{
"week":[
{
"access":16
}
]
},
"Site3":{
"week":[
{
"access":2
},
{
"access":6
},
{
"access":2
}
]
}
}
And I need to convert it into this format:
[
{
"id":"Site1",
"access":[1,8]
},
{
"id":"Site2",
"access":[16]
},
{
"id":"Site3",
"access":[2,6,2]
}
]
As you can see, I also need to take the keys (site name) and make them the "id" values.
Any ideas on how I can do this in JavaScript (I'm using angular v9)? I'm not very good at restructuring that type of data.
You can first take entries and then map it:
var data={ "Site1":{ "week":[ { "access":1 }, { "access":8 } ] }, "Site2":{ "week":[ { "access":16 } ] }, "Site3":{ "week":[ { "access":2 }, { "access":6 }, { "access":2 } ] }};
var result = Object.entries(data).map(([k,v])=>({id:k, access: v.week.map(p=>p.access)}));
console.log(result);
Object.keys()
map()
const data = {
Site1: {
week: [
{
access: 1,
},
{
access: 8,
},
],
},
Site2: {
week: [
{
access: 16,
},
],
},
Site3: {
week: [
{
access: 2,
},
{
access: 6,
},
{
access: 2,
},
],
},
};
const result = Object.keys(data).map(key => ({
id: key,
access: data[key].week.map(w => w.access),
}));
console.log(result);
you can simply use this code for your desired result.
Object.keys(data).map(key => (
{
id: key,
access: data[key].week.map(obj => obj.access),
}
))
Let me know if you face any issue.
Related
I want to pull with javascript: {"subNav0", "subNav1", "subNav2", "subNav3", "subNav4", "subNav5"}.
my json:
var data = {
"menus":{
"GrandparentNav0":{
"name":"TopNav",
"items":[
{
"name":"ParentNav0",
"iconClass":"",
"items":[
{
"name":"ParentNav1",
"iconClass":"",
"items":[
{
"name":"subNav0",
"iconClass":""
},
{
"name":"subNav1",
"iconClass":""
},
{
"name":"subNav2",
"iconClass":""
},
{
"name":"subNav3",
"iconClass":""
},
{
"name":"subNav4",
"iconClass":""
},
{
"name":"subNav5",
"iconClass":""
}
]
},
]
}
]
}
},
};
i know basic filter of an array:
data .forEach(function(o) {
o.variable = o.variable.filter(s => s.value == value);
});
I dont know how to get through menus, GrandparentNav0 to pull the subNav(s)
By "pull the subNav(s)" do you mean like accessing it through something like bracket notation?
let subNavs = data['menus']['GrandparentNav0']['items'][0]['items']
console.log(subNavs)
/* would return
[
{
"name": "subNav0",
"iconClass": ""
},
{
"name": "subNav1",
"iconClass": ""
},
{
"name": "subNav2",
"iconClass": ""
},
{
"name": "subNav3",
"iconClass": ""
},
{
"name": "subNav4",
"iconClass": ""
},
{
"name": "subNav5",
"iconClass": ""
}
]
*/
Here is a solution using object-scan. This might be overkill for your requirements, however as you run into other use cases it's a Swiss army knife that makes these types of data interactions very clean
// const objectScan = require('object-scan');
const data = { menus: { GrandparentNav0: { name: 'TopNav', items: [ { name: 'ParentNav0', iconClass: '', items: [ { name: 'ParentNav1', iconClass: '', items: [ { name: 'subNav0', iconClass: '' }, { name: 'subNav1', iconClass: '' }, { name: 'subNav2', iconClass: '' }, { name: 'subNav3', iconClass: '' }, { name: 'subNav4', iconClass: '' }, { name: 'subNav5', iconClass: '' } ] } ] } ] } } };
const result = objectScan(['menus.GrandparentNav0.items[0].items[0].items[*].name'], { reverse: false, rtn: 'value' })(data);
console.log(result);
// => [ 'subNav0', 'subNav1', 'subNav2', 'subNav3', 'subNav4', 'subNav5' ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#14.0.0"></script>
Disclaimer: I'm the author of object-scan
How can i add additional parameter inside of json using map function
How can I add selected false properties inside of menus array?
Here is the example of Json
const X = [
{
"detail1": "FirstJob",
"menus": [
{
"Order": 1,
"El": " Record Management",
"subSection": [
{
"El": "Check Notification",
"Order": "CheckNotification"
},
{
"El": "Check Record",
"Order": "CheckRecord"
}
]
},
{
"Order": 2,
"El": "Management",
"subSection": [
{
"El": "Notification",
"Order": "Notification"
},
{
"El": "Check",
"Order": "Check"
}
]
},
]
}
]
I tried this but it does add selected inside of the menus array
const filtered = X.map((item) => { return { ...item, selected: false }});
What if i want to add selected properties in subSection array ? how can that be implemnted?
You might need some deeper map
const newX = X.map((el) => ({
...el,
menus: el.menus.map((menuEl) => ({
...menuEl,
selected: false,
})),
}))
const X = [
{
detail1: "FirstJob",
menus: [
{
Order: 1,
El: " Record Management",
subSection: [
{
El: "Check Notification",
Order: "CheckNotification",
},
{
El: "Check Record",
Order: "CheckRecord",
},
],
},
{
Order: 2,
El: "Management",
subSection: [
{
El: "Notification",
Order: "Notification",
},
{
El: "Check",
Order: "Check",
},
],
},
],
},
]
const newX = X.map((el) => ({
...el,
menus: el.menus.map((menuEl) => ({
...menuEl,
selected: false,
})),
}))
console.log(newX)
You just have to extend the map to the subSection array as well.
const X = [{detail1:'FirstJob',menus:[{Order:1,El:' Record Management',subSection:[{El:'Check Notification',Order:'CheckNotification',},{El:'Check Record',Order:'CheckRecord',},],},{Order:2,El:'Management',subSection:[{El:'Notification',Order:'Notification',},{El:'Check',Order:'Check',},],},],},];
const getFormattedData = data => {
return data.map(d => {
return {
...d,
menus: d.menus.map(m => {
return {
...m,
subSection: m.subSection.map(s => {
return {
...s,
selected: false
}
})
}
})
}
})
}
console.log(getFormattedData(X));
.as-console-wrapper {
max-height: 100% !important;
}
Try this for adding selected at the top level
X.map(
item => {
item["selected"]=false;
return item;
}
);
and this for adding the selected field in the subSection
X.map(
item => {
item["menus"].map(
menuItem => {
menuItem["selected"] = true;
}
);
return item;
}
);
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' } ]
Hello all I have a question.
With this code:
targetingIdeaService.get({selector: selector}, function (error, result) {
var string = JSON.stringify(result)
console.log(string)
})
I get this result:
"totalNumEntries":700,
"entries":[
{
"data":[
{
"key":"KEYWORD_TEXT",
"value":{
"attributes":{
"xsi:type":"StringAttribute"
},
"Attribute.Type":"StringAttribute",
"value":"nike ddd8ea95"
}
},
{
"key":"COMPETITION",
"value":{
"attributes":{
"xsi:type":"DoubleAttribute"
},
"Attribute.Type":" DoubleAttribute",
"value":"0.8726547440705715"
}
},
{
"key":"AVERAGE_CPC",
"value":{
"attributes":{
"xsi:type":"MoneyAttribute"
},
"Attribute.Type":"MoneyAttribute",
"value":{
"ComparableValue.Type":"Money",
"microAmount":"16769286"
}
}
},
{
"key":"SEARCH_VOLUME",
"value":{
"attributes":{
"x si:type":"LongAttribute"
},
"Attribute.Type":"LongAttribute",
"value":"5609289"
}
}
]
}
]
}
And with this one i get the following:
targetingIdeaService.get({selector: selector}, function (error, result) {
var resultaten = result;
var res = resultaten.entries;
for(var i = 0; i < res.length; i++){
console.log(resultaten.entries[i])
}
})
Output
{ data:
[ { key: 'KEYWORD_TEXT', value: [Object] },
{ key: 'COMPETITION', value: [Object] },
{ key: 'AVERAGE_CPC', value: [Object] },
{ key: 'SEARCH_VOLUME', value: [Object] } ] }
Now im looking to format the JSON a certain way, It has to look like this example.
Notice: the key value pairs of json data.
[
{
"KEYWORD_TEXT": "red herring 9e23f4ad",
"SEARCH_VOLUME": 4574730
},
{
"KEYWORD_TEXT": "nike 656e95f0",
"SEARCH_VOLUME": 3442386
},
etc...
]
Basically the Key and the value of that key next to eachother. How to do this?
You can map the keys to values like following -
resultaten = result.data.map(function (item) {
return {
[item.key]: item.value
}
});
JSON.stringify(resultaten);
I am trying to pull an array from a different collection using collection2. I have been able to do this with objects using the following example for users:
users: {
type: String,
label: "Inspector",
optional: true,
autoform: {
firstOption: 'Choose an Inspector',
options: function() {
return Meteor.users.find({}, {
sort: {
profile: 1,
firstName: 1
}
}).map(function(c) {
return {
label: c.profile.firstName + " " + c.profile.lastName,
value: c._id
};
});
}
}
},
I would like to do the same but for an array of objects. Here is what the source data looks like:
{
"_id": "xDkso4FXHt63K7evG",
"AboveGroundSections": [{
"sectionName": "one"
}, {
"sectionName": "two"
}],
"AboveGroundItems": [{
"itemSection": "one",
"itemDescription": "dfgsdfg",
"itemCode": "dsfgsdg"
}, {
"itemSection": "two",
"itemDescription": "sdfgsdfg",
"itemCode": "sdfgsdgfsd"
}]
}
Here is what my function looks like:
agSection: {
type: String,
optional: true,
autoform: {
firstOption: 'Select A Section Type',
options: function() {
return TemplateData.find({}, {
sort: {
AboveGroundSections: 1,
sectionName: [0]
}
}).map(function(c) {
return {
label: c.AboveGroundSections.sectionName,
value: c.AboveGroundSections.sectionName
}
});
}
}
},
I know this, it's just not pulling the data for me. I am sure, I am just missing something small. I am trying to pull all objects within the AboveGroundSection array.
Your .map() is iterating over the set of documents but not over the arrays inside each document. Also I don't think your sorting is going to work the way you hope because of the inner nesting.
Try:
agSection: {
type: String,
optional: true,
autoform: {
firstOption: 'Select A Section Type',
options() {
let opt = [];
TemplateData.find().forEach(c => {
c.AboveGroundSections.forEach(s => { opt.push(s.sectionName) });
});
return opt.sort().map(o => { return { label: o, value: o } });
}
}
},
Also if your AboveGroundSections array only has a single key per element then you can simplify:
"AboveGroundSections": [
{ "sectionName": "one" },
{ "sectionName": "two" }
]
To:
"AboveGroundSections": [
"one",
"two"
]