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');
Related
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)
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.
so I am new in CouchDB and I was trying to write some python program that will upload a JSON file, upload a VIEW, and return me the values in an array.
I wrote the view as if(doc['city.berlin'])
emit(doc['city.berlin'], doc['city.berlin'])
So what are my best possibilities to extract the data into an array?
at the moment the return data in the terminal looks too complicated as it is giving back {ID, key, value}. Is there a simple method to save only the values?
Thanks
I'll assume your documents look like this
{
city: 'berlin',
x: 1,
y: 2
}
You can create a view that only indexes documents that have a city value of berlin with a map function like this:
function(doc) {
if (doc.city === 'berlin') {
emit(null, null)
}
}
In the above code, the if statement is choosing the subset of data that reaches the index. A more common pattern is to simply emit the city like so:
function(doc) {
emit(doc.city, null)
}
Now all of your data is in the index and at query-time you can choose which city's data to retrieve:
/db/_design/mydesigndoc/_view/myview?key="berlin"
The above query will retrieve the ids the documents where the key of the index (the city) matches the value you provide (berlin).
Adding include_docs=true retrieves the original docs in the response too:
/db/_design/mydesigndoc/_view/myview?key="berlin"&include_docs=true
You can also add one of the built-in reducers (_count, _sum or _stats) when creating the view to aggregate the data e.g. using the _count reduce, you can get a list of all the values of city and their counts with:
/db/_design/mydesigndoc/_view/myview?group=true
am getting json data as a response in the following format
{ '{"select":"samplec","value":"nation"}': '' }
How can i get a valid json data like
'{"select":"samplec", "value": "nation"}'
That is sort of an odd response to be getting, but in any case for this particular example you would do something like:
// Get the keys of your weird response object
var keys = Object.keys(response);
// The first key is a JSON string, so parse that
var obj = JSON.parse(keys[0]);
If the response had more than one key, you could loop through them all and create an array of objects. I would look into why the response was formatted the way it is, though, and see if you can't get the JSON strings delivered in some other way.
I'm trying to output a list of properties from a Mongoose object, but I get a lot of Javascript helper functions too. I'm wondering if there's a clean way to just output my Mongoose schema properties.
My Jade display code looks like:
h4 Legacy data
ul
- each val, key in d.old
li= key + ": " + val
And my Mongoose schema definition is
Entry = new Schema({
old : {
submitter : String,
table : String,
wordid : Number
}
});
But when the page is rendered, there are a bunch of other Javascript properties and functions that get outputted at the same time. e.g.
_scope: [object Object]
toObject: function () { return this.get(path); }
wordid: 2035
...
Is there an easy way to iterate just through the properties from my schema?
I could use a specified list but I was wondering if there was a nicer way.
Actually, how would I write the specified way? In ruby I know I could do [ 'wordid', 'submitter' ].each but is there an equivalent in Jade?
You're encountering the object's prototype properties. You can filter them out with .hasOwnProperty
- each val, key in d.old
- if(d.old.hasOwnProperty(key))
li= key + ": " + val
Remember that you can also use the method toJSON on the document (mongoose doc of Document#toJSON) to get a clean JSON object that can be used in your templates (without worrying about mongoose document's internals and methods). In fact, the toObject method you mentioned is similar to toJSON, you might wanna check it out.
For example:
doc = EntryModel({old: {submitter: "s", table: "tableS", wordid: "666"}})
console.log(b.toJSON())
// outputs:
{
"_id": "51fea037434b242816000002",
"old": {
"submitter": "s",
"table": "tableS",
"wordid": 666
}
}
// Is a plain JSON object without any other property or method