I have a json array
[{id:1,data:"test1"},{id:2,data:"test2"}]
I need to add a new element to each of the objects in the array based on the value of the "data" field. That is if the value of data is "test1", the new field data should be "test one type". The expected output is as below
[{id:1,data:"test1",type: "test1 Type"},{id:2,data:"test2",type: "test2 Type"}]
I tried with .push operation but it is adding new object to the array not updating the existing object. I am new to node NodeJs. Can you please help with this.
u need to map add element via map function
const data = [{id:1, data:"test1"},{id:2,data:"test2"}];
data.map(element => {
element.type = `${element.data} type`
return element;
});
console.log(data)
Related
I'm trying to achieve the functionality of dynamic table in Angular where data comes from backend first(Express) and then fills the data. I can also add new row to table and send data through it.
I'm able to successfully do it by sending all the data of table to API using formdata. Now I want is only the data which I've changed will be send to API and not the whole data.
This is my table:
On ngOnInit(), I'm calling API and saving data like this.collections = res.data
On Add Row, new row gets added with code:
addImage() {
const obj: Collection = {
uid: '',
image: '',
description: '',
price: ''
}
this.collections.push(obj)
}
On changing the text in input field, I'm using (input) property and passing the data to onInputChange()
onInputChange(text: string, i: string, property: string) {
this.collections[i][property] = text
}
Now my this.collections will have all the data which I'm send via POST API call on Save button i.e., all 3 rows here.
If I don't make any changes still this.collections will send that data. What I want is only changed data is send (like I changed only 1 row so only that data is send)
I tried achieving it by creating a new empty collecctionToAdd object and add data to it on onInputChange() like this, but since it is on (input) event, it keeps on changing for each text field.
if(this.collections[i][property] !== text) {
this.collectionToAdd[i][property] = text
}
Any idea or suggestions on how to achieve this?
Thanks in advance!
You can keep your "collecctionToAdd" logic.
I guess that you have a ngFor of "this.collections". So you need to do something like *ngFor="let item of collections; let i = index" in order to get the index of the element in the original collection an then:
initialize collecctionToAdd as empty Object:
private collecctionToAdd = {};
Make a function like this:
rowChange(text: string; field: string, index: number){
if(!this.collecctionToAdd[index]){
// use spread operator in order to keep the original object untouched or not. Remove it if u want
this.collecctionToAdd[index] = {...this.collecction[index]};
}
this.collecctionToAdd[index][field] = text;
}
and in your submit function:
submit(){
const rowsToSubmit = []
for (const key in this.collecctionToAdd) {
const element: any = this.collecctionToAdd[key];
rowsToSubmit.push(element);
}
}
NOTE: In the example i used "array syntax" in order to use variables for access and create propeties on object.
I am get the multiple fields from my document in firestore and then I use the data to set the same fields from the doc into another doc. There are a lot of fields in one document. How can I do this without writing each field name?
db.collection('sourceCollection').doc('sourceDoc').get().then( snap => {
const data = snap.data()
//from what I see this is an array now with fields in it
db.collection('newCollection').doc('newDoc').set({
//What do I put here so I can set the content of data as separate field in the newDoc
//if I do the following I get an array field called `data` within the new doc which is not what I want; I need the content of the `data` to be SEPARATE fields in the newDoc
data
//I also dont want to write each field because there are too many so the following wouldn't work for me:
fieldName: data.sourceDocFieldValue,
...
})
});
Just pass data without putting it in curly braces.
db.collection('newCollection').doc('newDoc').set(data);
I noticed that DynamoDB can add and remove items from an array but how do you search for an specific item inside an object if you want to update that one specifically?
For example:
In MongoDB you can search for someitem.$.subitem and update that specific item.
Is there a way on how to do this with DynamoDB?
Item: {
someitem: [
{
subitem: "id",
somevalue: "something"
}
]
}
I would say this is basic functionality but seems not easy to find (or even unsupported)
AWS does not permit to modify it in a single update request more info was found in the following answers:
updating-a-json-array-in-aws-dynamodb.
The solution that they propose is to change the schema from array to {}, or to implement a custom functions and iterate through each array and find your new id to update, so to speak to programatically update your json and then insert whole object.
TableName : 'tablename',
Key : { id: id},
ReturnValues : 'ALL_NEW',
UpdateExpression : 'set someitem['+`index`+'].somevalue = :reply_content',
ExpressionAttributeValues : { ':reply_content' : updateddata }
array element edit via array index
I am making a call to an API for a commercial product using Apps Script. Unfortunately, the resulting object has several key-value pairs that contain the id from a linked table.
I can easily get the standard values and have written code to find the related name value and add it to the object. I would prefer to add the name in the same location as the original id. But, when I add a new key, it is added to the end of the object.
I want the name in the same location as id so when I insert it into a sheet, the columns will still be in order.
This is my object:
var json = {id: 4730183,name: "A A", customer_source_id:123, company: "NE Company"};
This is my desired object after replacing the id with the name:
var json = {id: 4730183,name: "A A", source:"CRM", company: "NE Company"};
Basically, I want to find customer_source_id in the object and replace it with source.
I can't use indexOf and splice because the object is not an array.
What is the best way to do this? Do I have to convert it to an array first and then back again?
A quick answer would be:
var obj = {id: 4730183,name: "A A", customer_source_id:123, company: "NE Company"};
var json = JSON.stringify(obj);
json = json.replace("customer_source_id","source")
The better answer is:
#Waqar Ahmed is correct. JavaScript objects are unordered. In your example "var json" is an object not JSON. You can make it JSON with JSON.stringify(json). But once the JSON is parsed into an object it again becomes unordered. You should not use it to store ordered data.
I am not sure if it is efficient, but you can iterate through the keys and build a new json object like this:
var newjson = {};
for(var key in json){
if(key === 'customer_source_id'){
newjson.source = [NEW VALUE TO DISPLAY];
}else{
newjson[key] = json[key];
}
}
json = newjson;
But, like #Waqar and #Spencer said, the object is not used for ordered data.
You can do his only in java script array. Not in JSON. JSON is meant to be addressed by keys, not by index.Change your json to
var json ={id: 4730183,name: "A A", customer_source_id:null, items : [] company: "ESI"};
Now you can insert items using push method of array.
json.items.push('My Item');
I get this strange behavior. Here's the thing: I make a database query and want to delete an element of the json returned by the query. So this doesn't seem to work (i.e. the element is not deleted),
var user=json;
delete user.element;
while this works
var user={element:json.element,blement:'stuff'}
delete user.element;
I think what you are referring to as JSON is actually a Mongoose document object given the tags you added to your question. Since that object is attached to it's "schema", you may have rules in there such as a "required" field or such that are interfering with the operation you are trying to do.
In order to get a raw form of the Object back, simply use the .toObject() method on the document result:
Model.findOne({ _id: id}, function(err,doc) {
var raw = doc.toObject();
delete raw.element;
console.log( raw );
});
Of course you can always just omit the field from being returned in the query result with the basic form provided by .select():
Model.findOne({ _id: id}, '-element', function(err,doc) {
console.log( doc );
});
Either form would remove that particular field from the response, but if you possibly want more control over the result than what can be provided by the field projection from .select() then use the .toObject() form and manipulate just as a plain JavaScript object.