heres my output Image html How can I delete Object in array and push when adding some Data
angular.module('myApp.Tree_Service', [])
.factory('TreeService', function() {
var svc = {};
var treeDirectories = [
{
name: 'Project1',
id: "1",
type: 'folder',
collapse: true,
children: [
{
name: 'CSS',
id: "1-1",
type: 'folder',
collapse: false,
children: [
{
name: 'style1.css',
id: "1-1-1",
type: 'file'
},
{
name: 'style2.css',
id: "1-1-2",
type: 'file'
}
]
}
]
}
];
svc.add = function () {}
svc.delete = function (item, index) { }
svc.getItem = function () { return treeDirectories; }
return svc;
});
})();
I'm Newbee in Angularjs and I don't know how much to play it.
Hopefully someone can help me. Im Stucked.
Well you can delete any object by just usingdelete Objname.property
So for example you want to delete Children in treeDirectories first index object you can use delete treeDirectories[0].children if you want to delete children inside children then delete treeDirectories[0].children[0].children
if you want to remove an index from an array in lowest level children then
treeDirectories[0].children[0].children.splice(index,1)
for pushing data is for object you can directly assign value to the property you want
treeDirectories[0].children[0].newproperty = "check"
And for array you can
treeDirectories[0].children[0].children.push(object)
Related
Here I am trying to modify my data over the iteration and send some result to API call.
The API Call receives a request with a structured data format which is
{ list: [{ id: "1", name: "Hello" }, ... ] }
Somehow I managed to call the API with single data ( const params in my current code, it only accepts single data).
But now it has to be done with multiple data something like this:
{ list: [{ id: "1", name: "Hello" }, { id: "22", name: "Ed" }, { id: "36", name: "Jason" } ... ] }
Here is my current code
const [table, setTalbe] = useState(..); // assume, we have some table data here
const processNow = () => {
let id = 0;
let name = '';
// if table length is greater than 1, we go for the loop.
if (table.length >= 1) {
table.map(data => {
id = data.userId;
name = data.userName;
});
//insert table data to params, here I want to add whole table data into "list"
//the final result of this list should be something like this
//ex ) list: [{ id: '123', name: 'Josh' }, { id: '125', name: 'Sue' }, { id: '2222', name: 'Paker' } ...],
// but how??
const params: any = {
list: [
{
id: id,
name: name
},
],
};
//send PUT reqeust with params
axios
.put(
'/api/v1/tosent',
params,
)
.then(res => {
console.log('The response', res);
})
.catch(err => {
console.log('The error: ', err);
});
}
};
but I'm stuck with it, please help me to finish this code to work properly.
need your kind advice.
Array.prototype.map returns a new array with the function you pass applied to every element. You should study the MDN documentation on map to understand its use.
Your current code does nothing with the map return value:
table.map(data => {
id = data.userId;
name = data.userName;
});
You probably assumed .map would mutate the data, as in change it in place. Instead, the whole operation returns a new array.
It looks like you want to do:
const list = table.map(data => {
return {
id: data.userId,
name: data.userName
}
});
This is applying a function to every element in the array that will map each element to a new object, matching your question, with an id and name key. Then it looks like you want to pass the returned value of map (which we named list above) to your call:
const params: any = {
list: list
};
I am trying to create an array containing only id's from the state.words object (below)
MY REQUIRED OUTPUT
['word-1','word-2','word-3','word-4','word-5','word-6','word-7']
My starting data structure looks like this
words: {
'word-1': { id: 'word-1', content: 'Jimmy Yukka' ,url:'www.paulayling.me'},
'word-2': { id: 'word-2', content: 'INXS' ,url:'www.paulayling.me'},
'word-3': { id: 'word-3', content: 'Up North' ,url:'www.paulayling.me'},
'word-4': { id: 'word-4', content: 'Prince' ,url:'www.paulayling.me'},
'word-5': { id: 'word-5', content: 'Magic Moose' ,url:'www.paulayling.me'},
'word-6': { id: 'word-6', content: 'Salt n Pepper' ,url:'www.paulayling.me'},
'word-7': { id: 'word-7', content: 'Maddonna' ,url:'www.paulayling.me'}
}
The problem I have is that because it is an object array based methods will not give me the result I need eg below does not work - but I need an equivalent for an object of objects
My function is below
addNewWord() {
var currentOrder = this.state.words.map(function (book) {
return book.id
})
console.log('words stuff', currentOrder)
}
I get the error
TypeError: this.state.words.map is not a function
The function is called from the componentDidMount() function if it is relavant
map can only be used on arrays. If you want to list the keys in your words object, you can do it this way:
const result = Object.keys(this.state.words);
This will return your required output
I am working with ionic 3 and I have problems with an alert controller when I try to push an element in mi array. I do not what is wrong with my code, I think that I only need to receive the parameters and push it to complete the action but I only get a big error when I try to execute my code.
I'm so sorry, I know that my English is so bad.
CODE
addPregunta() {
const prompt = this.alertCtrl.create({
title: "Login",
message: "Enter a name for this new album you're so keen on adding",
inputs: [
{
name: "title",
placeholder: "Title"
}
],
buttons: [
{
text: "Cancel",
handler: data => {
console.log("Cancel clicked");
}
},
{
text: "Save",
handler: data => {
const preObj = {
type: "radio",
label: data.title
};
this.preguntas.push(preObj);
this.changeData(data.title);
this.mermaidStart();
}
}
]
});
prompt.present();
}
ARRAY
preguntas: object[];
ERROR
preguntas: object[]; The preguntas property is defined but it's not initialised with a value.
console.log(this.preguntas) // will be undefined
The problem is in the save handler:
{
text: "Save",
handler: data => {
const preObj = {
type: "radio",
label: data.title
};
this.preguntas.push(preObj); // <-- the problem is with this line
this.changeData(data.title);
this.mermaidStart();
}
When this.preguntas.push(preObj) is called for the first time. this.preguntas is undefined, array.push will not work because this.preguntas is not an array.
The options you have are to initialise the preguntas property as an array, or check the value in the handler before your call .push.
Option 1
Initialise the property as an array
preguntas: object[] = [];
Option 2
Check the value in the save handler before pushing.
There are countless ways to check or even use an immutable approach
// similar style with your existing code
if(this.preguntas) {
this.preguntas.push(preObj);
} else {
this.preguntas = [preObj];
}
// immutable approach
this.preguntas = [...this.preguntas, preObj]
You have declared the variable as an Array type but you did not initialize it so fails when you are trying to push into it.
So I have a problem with my var array to add a new chapter, how would I go about this would I have to do this:
array.push({
chapter: [
{
id: 2,
title: 'adsf',
content: '',
authorNotes: 'asdf'
}
]
});
RiTest.ts
import * as mongoose from 'mongoose';
const Scheme = mongoose.Schema;
export const RiTestScheme = new Scheme({
novelName: String,
novelAuthor: String,
novelCoverArt: String,
novelTags: Array,
chapters: [
{
id: Number,
title: String,
content: String,
authorNotes: String
}
]
});
export class RiTestController {
public addChapter(callback: (data) => void) {
var chapterInfoModel = mongoose.model('ChaptersTest', RiTestScheme);
var array = [
{
chapter: [
{
id: 0,
title: 'prolog',
content: 'conetntt is empty',
authorNotes: 'nothing is said by author'
},
{
id: 1,
title: 'making a sword',
content: 'mine craft end chapter',
authorNotes: 'nothing'
}
]
}
];
let newChapterInfo = new chapterInfoModel(array);
newChapterInfo.save((err, book) => {
if (err) {
return callback(err);
} else if (!err) {
return callback(book);
}
});
}
}
This doesn't work, var array doesn't get saved into let newChapterInfo = new chapterInfoModel(array); what I am trying to do add another chapter to array.chapter but the array doesn't get recognized in the chapterInfoModel() how would I fix this array and add an item to the array to create a new entry into this existing collection
thank for taking your time to answer my question.
You are trying to insert array of document to your collections, That the reason its not inserting into your collection.
Document.prototype.save() will insert only one document to your collection depends on your definition. So to insert chapter here is the code below,
//array as Object
var array = {
chapter: [
{
id: 0,
title: 'prolog',
content: 'conetntt is empty',
authorNotes: 'nothing is said by author'
},
{
id: 1,
title: 'making a sword',
content: 'mine craft end chapter',
authorNotes: 'nothing'
}
]
};
//Push to your chapter array
array.chapter.push({
id: 2,
title: 'adsf',
content: '',
authorNotes: 'asdf'
});
let newChapterInfo = new chapterInfoModel(array);
I am using something similar to the following schema.
By visiting the Item page I can add related items to the Item's Related Items array field.
I would like to custom validate the object I am pushing to the Item's Related Items field, to test if a similar object exists in the array already - so that I do not get a duplicate.
In my code below, the custom validation does not fire. I expect this may be because custom validation cannot be applied to a type: [object], and should be applied to the properties of the object - but then I am unable to test the object as a whole.
const ItemsSchema = new SimpleSchema({
name: {
type: String,
label: 'Name',
},
related: {
type: [Object],
label: 'Related Items',
optional:true,
custom: function () {
let queryData = { docId: this.docId, related: this.value }
if (Meteor.isClient && this.isSet) {
Meteor.call("relatedObjectIsUniqueForThisItem", queryData,
function (error, result) {
if(!result){
console.log("not unique");
return "Invalid";
}
else{
return true;
}
});
}
}
},
'related.$.name':{
type: String,
label:'Name',
},
'related.$.code':{
type:String,
label:'Code',
min:5,
},
});
I figured out the way to handle this.
The custom validation should not be on the [object], but rather one of the properties of the object - in this case 'source' or 'code'.
Inside one of the object properties you can call this.siblingField(otherField); But it means you have to rebuild the object.
In my case :-
const ItemsSchema = new SimpleSchema({
name: {
type: String,
label: 'Name',
},
related: {
type: [Object],
label: 'Related Items',
optional:true,
},
'related.$.name':{
type: String,
label:'Name',
custom: function () {
//---------------------------
//this is the important bit
//---------------------------
let queryData = {
docId: this.docId,
related: {
name:this.value,
code:this.siblingField('code').value,
}
}
//---------------------------
//end of important bit
//---------------------------
if (Meteor.isClient && this.isSet) {
Meteor.call("relatedObjectIsUniqueForThisItem", queryData,
function (error, result) {
if(!result){
console.log("not unique");
return "Invalid";
}
else{
return true;
}
});
}
}
},
'related.$.code':{
type:String,
label:'Code',
min:5,
},
});