I want to replace the value in existing JSON object in Node.js
Code :
var designationName='Softwar Engineer';
console.log(generateData[0]);
Console Output:
{
email: 'xxxxxx#gmail.com',
designation: 10,
id: 274,
first_name: 'firstname',
mobile: '1234567890',
last_name: 'lastname'
}
In the above console output 'designation' value printed as '10'
Expected Result:
I want to replace "designation: Software Engineer" instead of "designation:10"
Considering generateData[0] contains the following json which you fetch from a database
{
email: 'xxxxxx#gmail.com',
designation: 10,
id: 274,
first_name: 'firstname',
mobile: '1234567890',
last_name: 'lastname'
};
To replace "designation: Software Engineer" instead of "designation:10"
var designationName = 'Software Engineer';
if(generateData[0]){
generateData[0]['designation']= designationName;
}
console.log(generateData[0]);
var designationName='Softwar Engineer';
if( generateData.length && generateData[0].designation)
{
generateData[0].designation = designationName;
}
console.log(generateData[0]);
Related
I have been trying to fetch data out of JSON in flutter application.
I have tested the API request and formatting in python before making the application and all seems right
Python code:
for data in results['sections']:
for restaurant in data['items']:
restaurantName = restaurant['title']
restaurantImage = restaurant['image']['url']
for detail in restaurant:
if detail == 'venue':
restaurantAddress = restaurant['venue']['address']
restaurantDeliveryPrice = restaurant['venue']['delivery_price']
restaurantDeliveryETA = restaurant['venue']['estimate_range']
restaurantOnline = restaurant['venue']['online']
restaurantTags = restaurant['venue']['tags']
but when trying to get the data in flutter it doesn't return any feedback after
"for detail in restaurant:"
Dart code :
for (var data in jsonResponse['sections']) {
for (var restaurant in data['items']) {
var restaurantName = restaurant['title'];
var restaurantImage = restaurant['image']['url'];
print(restaurant);
}
}
Example restaurant json:
{filtering: {filters: [{id: primary, values: [hummus, kosher-for-passover, kosher]}]}, image: {blurhash: j6RIaL4iPuN3XKHdlktkX;OWgOmY, url: https://prod-wolt-venue-images-cdn.wolt.com/5fc619b23e62b6b24328928f/e122a0f8-3897-11eb-8333-de04af82ec5b_list1.jpg, variants: [xs, sm, md, frontpage]}, link: {target: 5fc619b23e62b6b24328928f, target_sort: default, target_title: , title: , type: venue-id, venue_mainimage_blurhash: j4OXin0g6J00Tl;;;mch7vgPV2WX}, overlay: Temporarily offline, sorting: {sortables: [{id: delivery-price, value: 1013}, {id: rating, value: 846}, {id: delivery-estimate, value: 946}, {id: distance, value: 1016}]}, template: venue-large, title: Hummus Hakerem | Shoken, track_id: venue-hummus-hakerem, venue: {address: שוקן 30 תל אביב , badges: [{text: KOSHER, variant: secondary}], categories: [], city: , country: ISR, currency: ILS, delivers: false, delivery_price: ₪18.00, delivery_price_highlight: false, delivery_price_int: 1800, estimate: 30, estimate_range: 25-35, franchise: , id: 5fc619b23e62b6b24328928f, location: [34.7720054, 32.0515629], name: Hummus Hakerem | Shoken, online: false, price_range: 1, product_line: restaurant, promotions: [], rating: {rating: 4, score: 9.2}, short_description: Simply great hummus, show_wolt_plus: false, slug: hummus-hakerem, tags: [kosher]}}
when trying to program the "for detail in restaurant:" loop in dart the app just loop endlessly
I am trying to make a PUT request for an object that doesn't contain an exact 'id' key. I am using the Angular InMemory Database service. The Object structure is as follows:
{
students: [{
name: 'jim',
age: 10,
grade: 4,
},{
name: 'james',
age: 11,
grade: 5,
}]
}
Service Method
updateStudent(student: Student) {
const url = 'api/students'
const options = { name: student.name };
return this.httpClient.put(url, student, { params: options }).pipe(
tap(_ => console.log('student updated)),
catchError(this.handleError('updating student'))
);
}
Component Method
updateStudent() {
this.studentService.updateStudent(this.selectedStudent).subscribe();
}
Where selectedStudent is:
{
name: 'jim',
age: 12,
grade: 6
}
If I change the PUT to a GET the in memory database come back with the correct student in the array. But with the code stated above I get a 404 Error
I m trying to convert an API response to typescript class/interface.
Here the API returns a list of objects with some properties, but I need only few of the properties of the response object.
API Response Example:
[{
'Id' : 1,
'Name': 'test',
'Description: 'Test',
'PropertyX': 'x',
'PropertyY' : 'y'
},
...]
Typescript Class
Class Response {
Id: string;
Name: string;
}
Can you please suggest me what will be the best approach for converting the JSON object to a typescript object.
I would suggest creating an interface that describes the properties you are using in your app and ignore the rest:
So assuming your response looks like:
const response = [{
'Id' : 1,
'Name': 'test',
'Description': 'Test',
'PropertyX': 'x',
'PropertyY' : 'y'
}, {
'Id' : 2,
'Name': 'test2',
'Description': 'Test2',
'PropertyX': 'x2',
'PropertyY' : 'y2'
}
];
and you are only interested in Id and Name, just create an interface like so:
interface IMyObject {
Id: String;
Name: String;
}
then in the rest of your app you can cast the response to IMyObject[]
For example if a function uses your response:
function myFunction(response: IMyObject[]) { ... }
or if you need to return that type, you can do a direct cast like so:
return response as MyObject[];
EDIT: As mentioned in the comment below, simply casting your object to IMyObject does not remove the extra properties you are not interested in.
To do so, use .map:
const formattedResponse: IMyObject = reponse.map(item => {
Id: item.Id,
Name: item.Name
});
You can use
forEach method and create a new object with the properties you require.
myarray=[];
ngOnInit() {
this.myvalues();
}
myMethod()
{
const response = [{
'Id' : 1,
'Name': 'test',
'Description': 'Test',
'PropertyX': 'x',
'PropertyY' : 'y'
}, {
'Id' : 2,
'Name': 'test2',
'Description': 'Test2',
'PropertyX': 'x2',
'PropertyY' : 'y2'
}
];
response.forEach(value=>{
this.myarray.push(
{
'ID':value.Id,
'Name':value.Name
}
)
});
console.log(this.myarray);
WORKING DEMO
I have a complicated data structure that I need to convert to JSON. The problem is that my field names and values are in an array.
For instance, I have the following (simplified from my code base):
let SampleData = [
{ Field: 'Key', Value: '7'},
{ Field: 'City', Value: 'Some City'},
{ Field: 'Description', Value: 'Some Description'}
];
Basically my data is an array where the first element is the database column name, and the second element is the data in the column. I am trying to get a JSON object that is:
{ Key: 7, City: 'Some City', Description: 'Some Description' }
My real code has the fields and data is structures within the object, so I cannot simply use an Object.create() or Object.assign() as far as I can get working.
I have tried looping through to build a simple string and then use the JSON.parse to break it apart, but this seems like a lot of overhead for something I would have thought would be simpler.
As you asked, here's how to do it:
Mapping the array to an object
Converting the object to JSON
let array = [{
Field: 'Key',
Value: '7'
},
{
Field: 'City',
Value: 'Some City'
},
{
Field: 'Description',
Value: 'Some Description'
}
];
// #1 Mapping the array to an object...
let obj = {};
array.forEach(item => obj[item.Field] = item.Value);
// #2 Converting the object to JSON...
let json = JSON.stringify(obj);
console.log(json);
Bonus (ES6 + reduce):
const obj = array.reduce((acc, { Field, Value }) => ({ ...acc, [Field]: Value }), {});
you can try the below approach . I have used spread operator(ES6) and Object.assign to create the object ,then converted it into json string.
let SampleData = [
{ Field: 'Key', Value: '7'},
{ Field: 'City', Value: 'Some City'},
{ Field: 'Description', Value: 'Some Description'}
];
let obj = Object.assign(...SampleData.map( x => Object.values(x)).map(y => ({[y[0]]: y[1]})));
console.log(obj);
//{ Key: "7", City: "Some City", Description: "Some Description" }
console.log(JSON.stringify(obj));
I had a similar requirement and here is how I achieved it.
var ranges: segmentRange[] = new Array(2);
ranges[0] = { minimumPercentage: 50, maximumPercentage: 60 };
ranges[1] = { minimumPercentage: 30, maximumPercentage: 40 };
const segmentRanges = { segmentRanges: ranges };
return JSON.stringify(segmentRanges);
Output:
{"segmentRanges":[{"minimumPercentage":50,"maximumPercentage":60},{"minimumPercentage":30,"maximumPercentage":40}]}
HTH,
I'm trying to use normalizer to normalize some JSON. My JSON looks like
total: 8029,
items: [
{
id: 1,
name: 'Jacket1',
sku: '123',
upc: '1',
price: '99.99',
images: ['url1', 'url2'],
category: 'clothing',
thumbnail:
'https://cdn.zeplin.io/5969021e44c5978909d5278b/assets/1CE5FF07-E70F-4413-85BF-49C08AA559DE.png',
}, ...
and from the examples, I thought this might work
const itemSchema = new schema.Entity('items')
const itemsSchema = new schema.Entity('result', {
items: [itemSchema],
})
const foo = normalize(fakeDatabase, itemsSchema)
But I end up with one result that is undefined, and that undefined value has some funky stuff in it.
What am I doing wrong?
I don't believe itemsSchema is necessary. Try either:
normalize(fakeDatabase, { items: new schema.Array(itemSchema) })
or
normalize(fakeDatabase, { items: [itemSchema] })