Getting [[Object]] when saving JSON - javascript

i am trying to save a json with "somewhere".
This function is incomplete but its enough to show the problem:
function testJSON(products) {
var productsPromises = products.map(function(product) {
var title = product['Title'];
var stock = product['Stock'];
var price = product['Price'];
if (stock == "Disponible") {
stock = true;
} else {
stock = false;
}
var toPush = [{Stock: stock, Price: price}];
var results = {Title: title, Results: toPush};
db.connect('./xxxxx/results.json');
var find = db.find('Productos', {Title: title});
console.log(find);
});
return Promise.all(productsPromises);
}
That returns:
[ { Title: 'Grabador de voz ISD1932',
Results: [ [Object] ],
id: 'f4099bff-fc55-4697-b712-d84343931818' } ]
[ { Title: 'Arduino SD Card Shield',
Results: [ [Object] ],
id: '75c79411-a905-41b3-9578-bb7072139a4d' } ]
[ { Title: 'Placa prototipo con zócalo para microSD Transflash',
Results: [ [Object] ],
id: 'af21962a-197e-43db-aba2-779be95357f2' } ]
[ { Title: 'Frontal para LCD 32PTU (Negro)',
Results: [ [Object] ],
id: '29d1e6cd-b549-44ad-87af-e4a4a056a609' } ]
I saved it same way but using
db.save('Productos', results); //instead of db.find(...
Why am i getting [[Object]] instead of the data? How can i fix this?

I suppose db.save('Productos', JSON.stringify(results)); should do it.

Related

Node 'Flatten/Merge' Array of Objects Containing Arrays and Display with forEach in EJS

Apologies for any repeats here, please point me in the direction of a solution if one exists.
Any other time, I seem able to display array data in ejs no problem, but this new flatten function has me stumped.
I have a nested array:
var array =
[{
page: {
results: [{
id: "1234",
type: "page",
title: "Deprecated Spec",
children: {
page: {
results: [{
id: "5678",
type: "page",
title: "Deprecated | Cash Spec"
},
{
id: "9101",
type: "page",
title: "Deprecated | Ledger Spec",
}
],
},
},
},
{
id: "1121",
type: "page",
title: "Work Spec"
}
]
}
}];
And I have a flatten function:
function flatten(arr) {
let flattened = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flattened = flattened.concat(flatten(arr[i]));
} else {
flattened.push(arr[i]);
}
}
return flattened;
}
I set a const and console.log:
const newArr = (flatten(array))
console.log(newArr);
In the terminal I receive: [ { page: { results: [Array] } } ]
For what it's worth, I've also tried flattening this nested array with these methods, and both return the same results.
const newArr2 = Array.prototype.concat.apply([], array);
const newArr3 = array.flat();
Hmm ok, I figure I can forEach and display the data on the .ejs page, which is set as:
<% newArr.forEach(function (newArr){ %>
<%= newArr.title %>
<% }) %>
But this shows nothing.
I have the res.render functioning properly as I am able to send and display other arrays/data sets.
If I try to "get into the array" with something like this: newArr[0].page.results, or any other variances, they don't work.
What am I missing to see my flattened array (using the recursive function) in both the console.log and on my ejs page?
UPDATED:
Per comments below, here is my desired output for the arrays and objects seen in var array:
[{
page: {
results: [
{
id: "1234",
type: "page",
title: "Deprecated Spec"
},
{
id: "5678",
type: "page",
title: "Deprecated | Cash Spec"
},
{
id: "9101",
type: "page",
title: "Deprecated | Ledger Spec"
},
{
id: "1121",
type: "page",
title: "Work Spec"
}
]
}
}];
Here is a pic of my current console.log
Many Thanks!
You should adapt your code to flatten the array like this to achieve the desired output:
const array = [
{
page: {
results: [
{
id: '1234',
type: 'page',
title: 'Deprecated Spec',
children: {
page: {
results: [
{
id: '5678',
type: 'page',
title: 'Deprecated | Cash Spec',
},
{
id: '9101',
type: 'page',
title: 'Deprecated | Ledger Spec',
},
],
},
},
},
{
id: '1121',
type: 'page',
title: 'Work Spec',
},
],
},
},
]
function flatten(arr) {
const flattened = []
for (const { children, ...element } of arr) {
flattened.push(element)
if (children) {
flattened.push(...flatten(children.page.results))
}
}
return flattened
}
const flat = [{ page: { results: flatten(array[0].page.results) } }]
console.log(flat)
console.log(flat[0].page.results)
// [
// {
// "page": {
// "results": [
// {
// "id": "1234",
// "type": "page",
// "title": "Deprecated Spec"
// },
// {
// "id": "5678",
// "type": "page",
// "title": "Deprecated | Cash Spec"
// },
// {
// "id": "9101",
// "type": "page",
// "title": "Deprecated | Ledger Spec"
// },
// {
// "id": "1121",
// "type": "page",
// "title": "Work Spec"
// }
// ]
// }
// }
// ]

Object gets duplicated inside array

This is the result I want to achieve
dataset: [
dataset: [
{
seriesname: "",
data: [
{
value: "123",
},
{
value: "123",
},
]
},
]
]
My problem right now is that the second dataset gets duplicated.
This is how I am setting it (val is an integer and allYears is an array of integers):
this.grphColumn.dataSource.dataset[0].dataset = this.allYears.map(el => {
return {
seriesname: "Planned",
data: [{value: val}, {value: val}]
}
});
How can I make it so the dataset doesn't get duplicated?
You have to map the values separately, if you dont want the seriesName to be Repeated..
const yearsMap = this.allYears.map((el) => { return { value: el } });
this.grphColumn.dataSource.dataset[0].dataset = {
seriesname: "Planned",
data: yearsMap
}

Loop over the array and display the following format

My goal is to loop over some data and get something like the following output, so if anyone can help me out it would be greatly appreciated. In order to display something like this, I tried looping something and displaying it in a loop.
let selectedOrders: {code?: string;selectedList?: [{ name: string; language: string }];
let set = new Set();
order.orders.map((list) => {
if (!set.has(list.code)) {
selectedOrders.push({
code: list.code,
selectedList: [
{
name: list.name!,
language: list.language!,
},
],
});
set.add(list.serviceCode);
return;
}
selectedOrders.push({
selectedList: [
{
name: list.name!,
language: list.language!,
},
],
});
}
});
return selectedOrders;
});
Input
{
code:"A"
name:"php"
desc:"language"
order:2
},
{
code:"A"
name:"javascript"
desc:"language"
order:1
},
Output
code: A
selectedList: [{
name:"javascript"
desc:"language"
},
{
name:"php"
desc:"language"
}]
}
let data = [
{
code: "A",
name: "php",
desc: "language",
order: 2,
},
{
code: "B",
name: "c++",
desc: "language",
order: 3,
},
{
code: "A",
name: "javascript",
desc: "language",
order: 1
}];
let result = data.reduce((acc: any[], item) => {
const { name, desc, order, code } = item;
if (acc.some((a: any) => code == a.code)) {
let obj: any = acc.find((a: any) => code == a.code)!;
obj.selectedList.push({
name, desc, order
});
} else {
acc.push({
code,
selectedList: [{ name, desc, order }]
});
}
return acc;
}, []);
console.log(result);
Just change any to your required type.

Create a key map for all paths in a recursive/nested object array

I have an n levels deep nested array of tag objects with title and ID. What I'm trying to create is a an object with IDs as keys and values being an array describing the title-path to that ID.
I'm no master at recursion so my attempt below doesn't exactly provide the result I need.
Here's the original nested tag array:
const tags = [
{
title: 'Wood',
id: 'dkgkeixn',
tags: [
{
title: 'Material',
id: 'ewyherer'
},
{
title: 'Construction',
id: 'cchtfyjf'
}
]
},
{
title: 'Steel',
id: 'drftgycs',
tags: [
{
title: 'Surface',
id: 'sfkstewc',
tags: [
{
title: 'Polished',
id: 'vbraurff'
},
{
title: 'Coated',
id: 'sdusfgsf'
}
]
},
{
title: 'Quality',
id: 'zsasyewe'
}
]
}
]
The output I'm trying to get is this:
{
'dkgkeixn': ['Wood'],
'ewyherer': ['Wood', 'Material'],
'cchtfyjf': ['Wood', 'Construction'],
'drftgycs': ['Steel'],
'sfkstewc': ['Steel', 'Surface'],
'vbraurff': ['Steel', 'Surface', 'Polished'],
'sdusfgsf': ['Steel', 'Surface', 'Coated'],
'zsasyewe': ['Steel', 'Quality']
}
So I'm building this recursive function which is almost doing it's job, but I keep getting the wrong paths in my flat/key map:
function flatMap(tag, acc, pathBefore) {
if (!acc[tag.id]) acc[tag.id] = [...pathBefore];
acc[tag.id].push(tag.title);
if (tag.tags) {
pathBefore.push(tag.title)
tag.tags.forEach(el => flatMap(el, acc, pathBefore))
}
return acc
}
const keyMap = flatMap({ title: 'Root', id: 'root', tags}, {}, []);
console.log("keyMap", keyMap)
I'm trying to get the path until a tag with no tags and then set that path as value for the ID and then push the items 'own' title. But somehow the paths get messed up.
Check this, makePaths arguments are tags, result object and prefixed titles.
const makePaths = (tags, res = {}, prefix = []) => {
tags.forEach(tag => {
const values = [...prefix, tag.title];
Object.assign(res, { [tag.id]: values });
if (tag.tags) {
makePaths(tag.tags, res, values);
}
});
return res;
};
const tags = [
{
title: "Wood",
id: "dkgkeixn",
tags: [
{
title: "Material",
id: "ewyherer"
},
{
title: "Construction",
id: "cchtfyjf"
}
]
},
{
title: "Steel",
id: "drftgycs",
tags: [
{
title: "Surface",
id: "sfkstewc",
tags: [
{
title: "Polished",
id: "vbraurff"
},
{
title: "Coated",
id: "sdusfgsf"
}
]
},
{
title: "Quality",
id: "zsasyewe"
}
]
}
];
console.log(makePaths(tags));

Flattened Array with Objects

I'm certain this question is very common, but I can't seem to find a robust answer for my use case.
I have an Array of objects with nesting in two levels. Here is an example of the array:
let array = [
{ company: 'CompanyName1',
child: [
{ title: 'title1a',
baby: [
{ title: 'title1ab' },
{ title: 'title1abc' }
]
},
{ title: 'title2a',
baby: [
{ title: 'titleb2abcd' },
{ title: 'titleb2abcde' }
]
}
]
},
{ company: 'CompanyName2',
child: [
{ title: 'title2b',
baby: [
{ title: 'titleb3ab' },
{ title: 'titleb3abc' }
]
}
]
}
]
And this is my expected Array:
let newArray = [
{
company: 'companyName1',
child_title_0: 'title1a',
child_title_1: 'title1a',
child_baby_0: 'title1ab',
child_baby_1: 'title1abc',
child_baby_2: 'title1abcd',
child_baby_3: 'title1abcde',
},
{
company: 'companyName2',
child_title_0: 'title2b',
child_baby_0: 'titleb3ab',
child_baby_1: 'titleb3abc',
}
]
Basically I need to flatten each of the top level objects of the array. Since the nested objects have the same keys (follow a model, and are dynamic -- some items have 10 nested objects, some 0, etc.) I have to dynamically generate each of the new keys, possibly based in the index of the loops.
Any help -- direction is appreciated.
Thanks!
You can use the map function to return a manipulated version of each object in the array.
let results = [
{
company: 'CompanyName1',
child: [
{
title: 'title1a',
baby: [
{ title: 'title1ab' },
{ title: 'title1abc' }
]
},
{
title: 'title2a',
baby: [
{ title: 'titleb2abcd' },
{ title: 'titleb2abcde' }
]
}
]
},
{
company: 'CompanyName2',
child: [
{
title: 'title2b',
baby: [
{ title: 'titleb3ab' },
{ title: 'titleb3abc' }
]
}
]
}
];
let flattened = results.map(company => {
let childCount = 0, babyCount = 0;
company.child.forEach(child => {
company['child_title_'+childCount] = child.title;
child.baby.forEach(baby => {
company['child_baby_'+babyCount] = baby.title;
babyCount++;
});
childCount++;
});
delete company.child;
return company;
});
console.log(flattened);

Categories

Resources