Push an Object Into a complicated arra - javascript

I'm trying to push an Object into a complicated array I'm thinking about something like that"DUMMY_PLACES[0].todos.byIds.push" but I don't succeed to do it. I have an(id, content), and the completed need to be by default false. hope for help I believe that's not too complicated but I can't figure it out. ps: if someone can also help with the delete option I would be happy.
for example, I get (5,test5). I want.
const DUMMY_PLACES = [
{
todos: {
allIds: [1, 2, 3, 4,],
byIds: {
"1": {
content: "test1",
completed: false,
},
"2": {
content: "test2",
completed: false,
},
"3": {
content: "test3\\",
completed: false,
},
"4": {
content: "test4",
completed: false,
},
},
},
visibilityFilter: "all",
},
];
const DUMMY_PLACES = [
{
todos: {
allIds: [1, 2, 3, 4,5],
byIds: {
"1": {
content: "test1",
completed: false,
},
"2": {
content: "test2",
completed: false,
},
"3": {
content: "test3\\",
completed: false,
},
"4": {
content: "test4",
completed: false,
},
"5": {
content: "test5",
completed: false,
},
},
},
visibilityFilter: "all",
},
];

Here take a look at the addTodo function which creates a new instance of the todoList with a new element added to the end of it. And it also modifies the list of Ids. I've commented almost every line, so it should be pretty straightforward.
let todoList = [
{
todos: {
allIds: [1, 2, 3, 4],
byIds: {
"1": {
content: "test1",
completed: false,
},
"2": {
content: "test2",
completed: false,
},
"3": {
content: "test3",
completed: false,
},
"4": {
content: "test4",
completed: false,
},
},
},
visibilityFilter: "all",
},
];
let addTodo = (sourceArray, el) => {
// Create a copy of an original array
let targetArray = [];
Object.assign(targetArray, sourceArray);
let todos = targetArray[0].todos;
// Calculate the Id for a new element
let newId = Object.keys(todos.byIds).length + 1;
// Add new Id to the `allIds` list
todos.allIds.push(newId);
// Create a new element
todos.byIds[newId] = {
content: el,
completed: false
}
return targetArray;
}
todoList = addTodo(todoList, 'test5');
todoList = addTodo(todoList, 'test6');
todoList = addTodo(todoList, 'test7');
console.log(JSON.stringify(todoList));
And the output should be:
[
{
"todos":{
"allIds":[
1,
2,
3,
4,
5,
6,
7
],
"byIds":{
"1":{
"content":"test1",
"completed":false
},
"2":{
"content":"test2",
"completed":false
},
"3":{
"content":"test3",
"completed":false
},
"4":{
"content":"test4",
"completed":false
},
"5":{
"content":"test5",
"completed":false
},
"6":{
"content":"test6",
"completed":false
},
"7":{
"content":"test7",
"completed":false
}
}
},
"visibilityFilter":"all"
}
]

Maybe you need something like this
const DUMMY_PLACES = [ { todos: { allIds: [1, 2, 3, 4], byIds: { "1": { content: "test1", completed: false, }, "2": { content: "test2", completed: false, }, "3": { content: "test3\\", completed: false, }, "4": { content: "test4", completed: false, }, }, }, visibilityFilter: "all", }, ];
function pushObject(id, content) {
DUMMY_PLACES[0].todos.allIds.push(id);
DUMMY_PLACES[0].todos.byIds[id] = { ...content, completed: false };
}
pushObject(5, { content: "test5" });
console.dir(DUMMY_PLACES);

Your code lacks encapsulation. Best approach here would be to create a new class and create a setter for this.
EDIT with example:
class UserTodo
{
constructor( visibilityFilter = 'all' )
{
this._visibilityFilter = visibilityFilter;
this._byIds = new Map();
}
/**
* #details Add a todo with the content text
*/
addTodo( title, content )
{
const value = {
content,
completed: false
}
this._byIds.set( title, value );
}
/**
* #Details Decide if you want to get the entire object or just the content here
*/
getTodo( title )
{
return this._byIds.get( title );
}
completeTodo( title )
{
this._byIds.get( title ).completed = true;
}
/**
* #details As a bonus on how to delete a specific todo
*/
deleteTodo( title )
{
this._byIds.delete( title );
}
/**
* #details this will return allIds from the example
*/
getAllIds()
{
return Array.from( this._byIds.keys() );
}
/**
* #details this will return visibilityFilter from the example
*/
getVisibility()
{
return this._visibilityFilter;
}
// Implement other getters
}
// Why is this an array even?
const DUMMY_PLACES = [];
DUMMY_PLACES.push( new UserTodo( 'all' ) );
const toDoTitle = 'Some Title';
// Add a new todo
DUMMY_PLACES[0].addTodo( toDoTitle, 'Do Something' );
// Check that the todo is added
console.log( DUMMY_PLACES[0].getTodo( toDoTitle ) );
// Complete it
DUMMY_PLACES[0].completeTodo( toDoTitle );
// Check that it is completed
console.log( DUMMY_PLACES[0].getTodo( toDoTitle ) );

Related

Combine duplicate tokens inside huge JSON file into nested array of objects using React

I looked at several of the suggested solutions but none seemed to rise to this confounding data formatting challenge.
I have a huge JSON file (over 100k rows) and massive duplicates of data all as top level objects. Here's an example:
[
{
"manufacturer":"Samsung",
"device":"Galaxy A32 5G",
"model":"SM-A326B",
"chipset":"Mediatek MT6853V/NZA",
"date":"2022-01-01",
"fw_id":"A326BXXS4AVA1",
"android":"R(Android 11)",
"known_passcode":false,
"afu":false,
"bfu":false,
"bruteforce":false
},
{
"manufacturer":"Samsung",
"device":"Galaxy A32 5G",
"model":"SM-A326U",
"chipset":"Mediatek MT6853V/NZA",
"date":"2021-03-01",
"fw_id":"A326USQU1AUD4",
"android":"R(Android 11)",
"known_passcode":true,
"afu":false,
"bfu":true,
"bruteforce":true
},
{
"manufacturer":"Samsung",
"device":"Galaxy A32 5G",
"model":"SM-A326U1",
"chipset":"Mediatek MT6853V/NZA",
"date":"2021-09-01",
"fw_id":"A326U1UEU5AUJ2",
"android":"R(Android 11)",
"known_passcode":true,
"afu":false,
"bfu":true,
"bruteforce":true
},
{
"manufacturer":"LGE",
"device":"LG K31",
"model":"LGL355DL",
"chipset":"Mediatek MT6762",
"date":"unknown",
"fw_id":"L355DL10l",
"android":"unknown",
"known_passcode":false,
"afu":false,
"bfu":false,
"bruteforce":false
}
]
This needs to be organized so that data points like manufacturer, device, model are not duplicated hundreds of times.
Btw, here's a JSFiddle to play with:
https://jsfiddle.net/xpancom/Lq7duahv/
Ideally, the JSON format would be the following:
[
{
"manufacturers": [
{
"manufacturer": "Samsung",
"devices": [
{
"device": "Galaxy A32 5G",
"models": [
{
"model": "SM-A326B",
"data": [
{
"chipset": "Mediatek MT6853V/NZA",
"date": "2022-01-01",
"fw_id": "A326BXXS4AVA1",
"android": "R(Android 11)",
"known_passcode": false,
"afu": false,
"bfu": false,
"bruteforce": false
},
{
"chipset": "Mediatek MT6853V/NZA",
"date": "2021-09-01",
"fw_id": "A326BXXU3AUH7",
"android": "R(Android 11)",
"known_passcode": true,
"afu": false,
"bfu": true,
"bruteforce": true
}
]
},
{
"model": "SM-A326U1",
"data": [
{
"chipset": "Mediatek MT6853V/NZA",
"date": "2021-09-01",
"fw_id": "A326U1UEU5AUJ2",
"android": "R(Android 11)",
"known_passcode": true,
"afu": false,
"bfu": true,
"bruteforce": true
}
]
}
]
}
]
},
{
"manufacturer": "LGE",
"devices": [
{
"device": "LG K31",
"models": [
{
"model": "SM-A326B",
"data": [
{
"chipset": "Mediatek MT6762",
"date": "unknown",
"fw_id": "L355DL10l",
"android": "unknown",
"known_passcode": false,
"afu": false,
"bfu": false,
"bruteforce": false
}
]
}
]
}
]
}
]
}
]
Working in React, here's what I've got so far in trying to massage this data:
const source = data;
const destination = [];
const classifiedTokens = []; // will be used to stored already classified tokens
const classifiedTokensModel = []; // will be used to stored already classified tokens for models
const getNextTokenArray = (source) => {
let unusedToken = null;
const nextTokenArray = source.filter(function (element) {
if (!unusedToken && !classifiedTokens.includes(element['device'])) {
unusedToken = element['device'];
classifiedTokens.push(unusedToken);
}
return unusedToken ? unusedToken === element['device'] : false;
});
return unusedToken ? nextTokenArray : null;
};
// Pass in arrays deconstructed from addToDestination to process third tier nested objects for models
const getNextTokenArrayModel = (tokenObject) => {
let tokenObjectDevice = tokenObject['device'];
let tokenObjectData = tokenObject['data'];
let unusedTokenModel = null;
const nextTokenArrayModel = tokenObjectData.filter(function (element) {
if (!unusedTokenModel && !classifiedTokensModel.includes(element['model'])) {
unusedTokenModel = element['model'];
classifiedTokensModel.push(unusedTokenModel);
}
return unusedTokenModel ? unusedTokenModel === element['model'] : false;
});
//return unusedTokenModel ? nextTokenArrayModel : null;
if (unusedTokenModel) {
if (nextTokenArrayModel.length === 0) return;
let res = {
device: tokenObjectDevice,
model: nextTokenArrayModel[0]['model'],
data: [],
};
nextTokenArrayModel.forEach((element) => {
res.data.push({
manufacturer: element.manufacturer,
chipset: element.chipset,
date: element.date,
fw_id: element.fw_id,
android: element.android,
knownPasscode: element.knownPasscode,
afu: element.afu,
bfu: element.bfu,
bruteforce: element.bruteforce,
});
});
destination.push(res);
} else {
return null;
}
};
const addToDestination = (tokenArray) => {
if (tokenArray.length === 0) return;
let res = {
device: tokenArray[0]['device'],
data: [],
};
tokenArray.forEach((element) => {
res.data.push({
manufacturer: element.manufacturer,
model: element.model,
chipset: element.chipset,
date: element.date,
fw_id: element.fw_id,
android: element.android,
knownPasscode: element.knownPasscode,
afu: element.afu,
bfu: element.bfu,
bruteforce: element.bruteforce,
});
});
getNextTokenArrayModel(res); // Call this to process and group nested model duplicates by device
//destination.push(res);
};
let nextTokenArray = getNextTokenArray(source);
while (nextTokenArray) {
addToDestination(nextTokenArray);
nextTokenArray = getNextTokenArray(source);
}
setTimeout(() => {
document.getElementById('root').innerHTML =
'<pre>' + JSON.stringify(destination, null, 2) + '</pre>';
}, 1000);
};
And here's the JSFiddle again:
https://jsfiddle.net/xpancom/Lq7duahv/
Who can smash this data formatting dilemma?
This answer is not React specific, but one approach would be to use array.reduce() to transform each level/node of the structure as shown in the code snippet below.
const source = [
{
manufacturer: 'Samsung',
device: 'Galaxy A32 5G',
model: 'SM-A326B',
chipset: 'Mediatek MT6853V/NZA',
date: '2022-01-01',
fw_id: 'A326BXXS4AVA1',
android: 'R(Android 11)',
known_passcode: false,
afu: false,
bfu: false,
bruteforce: false,
},
{
manufacturer: 'Samsung',
device: 'Galaxy A32 5G',
model: 'SM-A326B',
chipset: 'Mediatek MT6853V/NZA',
date: '2022-01-01',
fw_id: 'A326BXXS4AVA1',
android: 'R(Android 11)',
known_passcode: false,
afu: false,
bfu: false,
bruteforce: false,
},
{
manufacturer: 'Samsung',
device: 'Galaxy A32 5G',
model: 'SM-A326U',
chipset: 'Mediatek MT6853V/NZA',
date: '2021-03-01',
fw_id: 'A326USQU1AUD4',
android: 'R(Android 11)',
known_passcode: true,
afu: false,
bfu: true,
bruteforce: true,
},
{
manufacturer: 'Samsung',
device: 'Galaxy A32 5G',
model: 'SM-A326U1',
chipset: 'Mediatek MT6853V/NZA',
date: '2021-09-01',
fw_id: 'A326U1UEU5AUJ2',
android: 'R(Android 11)',
known_passcode: true,
afu: false,
bfu: true,
bruteforce: true,
},
{
manufacturer: 'LGE',
device: 'LG K31',
model: 'LGL355DL',
chipset: 'Mediatek MT6762',
date: 'unknown',
fw_id: 'L355DL10l',
android: 'unknown',
known_passcode: false,
afu: false,
bfu: false,
bruteforce: false,
},
];
function generateTree(data, key) {
return data.reduce((acc, val) => {
// Split the key name from the child data
const { [key.name]: keyName, ...childData } = val;
// Find a tree item in the structure being generated
const treeItem = acc.find((item) => item[key.name] === keyName);
if (treeItem) {
// If found, append child data
treeItem[key.child].push(childData);
} else {
// If not found, create new key and append child data
acc.push({ [key.name]: keyName, [key.child]: [childData] });
}
return acc;
}, []);
}
// Generate manufacturer/device structure
const manufacturers = generateTree(source, {
name: 'manufacturer', // Key name to use as grouping identifier
child: 'devices', // Key name for child data
});
// Generate device/model structure
manufacturers.forEach((manufacturer) => {
manufacturer.devices = generateTree(manufacturer.devices, {
name: 'device',
child: 'models',
});
// Generate model/data structure
manufacturer.devices.forEach((device) => {
device.models = generateTree(device.models, {
name: 'model',
child: 'data',
});
});
});
const destination = [{ manufacturers }];
console.log(destination);

Comparison of two arrays regarding the text

I've got two arrays which i want to compare. Therfore i want to check if they got equal elements regarding the "text": .... If its equal it should return true, otherwise return false
englishData = [
{"data":"sandwich","text":"Sandwich"},
{"data":"toast","text":"Cuisine"},
{"data":"fries","text":"Pommes"},
{"data":"salad","text":"Salad"},
]
franceData = [
{"data":"sandwich","text":"Sandwich"},
{"data":"toast","text":"Kitchen"},
{"data":"fries","text":"Pommes"}]
So far i tried it with a normal for-loop, like :
for (let i = 0; i < actualData; i++) {
for (let j = 0; j < plannedData; j++) {
if (actualData[i].text === plannedData[i].text) {
return true
} if (actualData[i].text != plannedData[j].text) {
continue;
}
}
return false
}
}
Because of the different length, i wanted to compare each element in franceData with all elements in the original array englishData.
Its kinda woking, but im not sure if it's really the best solution regarding the performance, ... .
I also thought about some if statements, like:
if(franceData.text.includes(englishData.text)){ return true }
If you are looking to find out common elements, you can try something like this
englishData = [
{ data: "sandwich", text: "Sandwich" },
{ data: "toast", text: "Cuisine" },
{ data: "fries", text: "Pommes" },
{ data: "salad", text: "Salad" },
];
franceData = [
{ data: "sandwich", text: "Sandwich" },
{ data: "toast", text: "Kitchen" },
{ data: "fries", text: "Pommes" },
];
var res = englishData.filter((ede) =>
franceData.some((fde) => ede.text === fde.text)
);
console.log(res);
output:
[
{ data: 'sandwich', text: 'Sandwich' },
{ data: 'fries', text: 'Pommes' }
]
You can use map() in the place of filter to get just true or false for every match.
englishData = [
{ data: "sandwich", text: "Sandwich" },
{ data: "toast", text: "Cuisine" },
{ data: "fries", text: "Pommes" },
{ data: "salad", text: "Salad" },
];
franceData = [
{ data: "sandwich", text: "Sandwich" },
{ data: "toast", text: "Kitchen" },
{ data: "fries", text: "Pommes" },
];
var res = englishData.map((ede) =>
franceData.some((fde) => ede.text === fde.text)
);
console.log(res.join("\n"));
output:
true
false
true
false

How to append data in json using map function?

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;
}
);

Add tasks for todo list

I am trying to add tasks for each todo list that has a specific title.
Can I get a specific todo list by its id and add some tasks to it?
I am new to javascript, so I searched google about adding lists for a specific list with no results :(
class Model {
constructor() {}
this.todos = [
{
id: 1,
title: 'Outside',
text: 'Running',
complete: false,
tasks: [
{ id: 1, text: 'Run a marathon', complete: false},
{ id: 2, text: 'Run with freinds', complete: false}
]
},
{
id: 2,
title: 'Garden',
text: 'Plant',
complete: false,
tasks: [
{ id: 1, text: 'Plant a garden', complete: false},
{ id: 2, text: 'Water the garden', complete: false}
]
}];
addTodo(todoText) {
const todo = {
id: this.todos.length > 0 ? this.todos[this.todos.length - 1].id + 1 : 1,
text: todoText,
complete: false,
tasks: []
}
this.todos.push(todo)
}
}
Is it true to do like addTodo function for adding a tasks for a specific todo list like this?
addTodoTask(todoTaskText) {
const todoTask = {
id: this.todos.tasks.length > 0 ? this.todos[this.todos.tasks.length - 1].id + 1 : 1,
text: todoText,
complete: false,
}
this.todos.tasks.push(todoTask)
}
and how to add a list of a list in javascript like:
<ul>
<li>Running
<ul>
<li>Run a marathon</li>
<li>Run with freind</li>
</ul>
</li>
</ul>
You could make each class handle rendering its own content and just map the list items consecutively while rendering from the top-down.
Edit: The render() methods make use of ES6 template literals. These are special strings that allow you embed variabes and expressions without the use of string concatenation.
const main = () => {
let todoList = new TodoList({ todos : getData() })
document.body.innerHTML = todoList.render()
}
class TodoTask {
constructor(options) {
this.id = options.id
this.text = options.text
this.complete = options.complete
}
render() {
return `<li>[${this.id}] ${this.text} (${this.complete})</li>`
}
}
class TodoEntry {
constructor(options) {
this.id = options.id
this.title = options.title
this.text = options.text
this.complete = options.complete
this.tasks = []
if (options.tasks) {
options.tasks.forEach(task => this.addTask(task))
}
}
addTask(task) {
this.tasks.push(new TodoTask(Object.assign({
id : (this.tasks.length || 0) + 1
}, task)))
}
render() {
return `<li>
[${this.id}] ${this.title} (${this.complete})
<ul>${this.tasks.map(task => task.render()).join('')}</ul>
</li>`
}
}
class TodoList {
constructor(options) {
this.todos = []
if (options.todos) {
options.todos.forEach(todo => this.addTodo(todo))
}
}
addTodo(todo) {
this.todos.push(new TodoEntry(Object.assign({
id : (this.todos.length || 0) + 1
}, todo)))
}
render() {
return `<ul>${this.todos.map(todo => todo.render()).join('')}</ul>`
}
}
function getData() {
return [{
id: 1,
title: 'Outside',
text: 'Running',
complete: false,
tasks: [{
id: 1,
text: 'Run a marathon',
complete: false
}, {
id: 2,
text: 'Run with freinds',
complete: false
}]
}, {
id: 2,
title: 'Garden',
text: 'Plant',
complete: false,
tasks: [{
id: 1,
text: 'Plant a garden',
complete: false
}, {
id: 2,
text: 'Water the garden',
complete: false
}]
}]
}
main() // entry
To add a task your todo, you should have a way of knowing which todo list you're updating. Like using the todo's id.
For example your addTaskToTodo will looks like so.
addTask(todoId, taskObject) {
// find that todos index
const todoIndex = this.todos.findIndex(todo => todo.id ===todoId);
// using that index update the tasks
this.todos[todoIndex].tasks.push(taskObject)
}
This assumes your taskObject already has all the properties. If you need to manually update its id, you can also do that before pushing by checking the length of the tasks and incrementing by 1.
I made an example of how to use dictionaries instead of arrays, and also a random ID. I think you will find it much cleaner and simpler:
class Model {
constructor() { }
todos = {
1: {
id: 1,
title: 'Outside',
text: 'Running',
complete: false,
tasks: {
1: { id: 1, text: 'Run a marathon', complete: false },
2: { id: 2, text: 'Run with freinds', complete: false }
}
},
2: {
id: 2,
title: 'Garden',
text: 'Plant',
complete: false,
tasks: {
1: { id: 1, text: 'Plant a garden', complete: false },
2: { id: 2, text: 'Water the garden', complete: false }
}
}
}
getRandomId = () => {
return '_' + Math.random().toString(36).substr(2, 9);
}
addTodo(todoText) {
const id = this.getRandomId();
const todo = {
id,
text: todoText,
complete: false,
tasks:{}
}
this.todos[id] = todo;
}
addTodoTask(todoTaskText,todoId) {//Pass also the id of the todo, to know where this task belongs to.
const id = this.getRandomId();
const todoTask = {
id,
text: todoTaskText,
complete: false,
}
this.todos[todoId].tasks[id] = todoTask
}
}
This way you could easily edit/remove both todos and tasks, just by their id, without using any messy Array.filter and such

Meteor cross collection arrays

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"
]

Categories