Replacement in a json array - Angular - json

I am trying to replace an object in my json web server array : If an object with a similar id is already in the json array.
This is my json array :
{
"history": [
{
"id": 4,
"SNS": "BockeSinoJutsu-SNS",
"title": "BockeSinoJutsu-title",
"DMC": "BockeSinoJutsu-DMC",
"date": "June 15 2022"
},
{
"id": 1,
"SNS": "Rasengan-SNS",
"title": "Rasengan-title",
"DMC": "Rasengan-DMC",
"date": "2022-06-18T17:43:59.708Z"
}
]
}
And this is the json file I am comparing it to :
{
"content":[
{
"id":1,
"SNS":"Rasengan-SNS",
"title":"Rasengan-title",
"DMC":"Rasengan-DMC"
},
{
"id":2,
"SNS":"Mangekyu-SNS",
"title":"Mangekyu-title",
"DMC":"Mangekyu-DMC"
},
{
"id":3,
"SNS":"Chidori-SNS",
"title":"Chidori-title",
"DMC":"Chidori-DMC"
}
]
}
This is what I have tried :
onAddHistory(history:History){
history.date = new Date();
console.log(history.SNS);
this.historyService.getHistory().subscribe(
(response:History[])=>{
this.ExistingHistory=response.filter(x => x.id === history.id);
console.log(this.ExistingHistory);
if(this.ExistingHistory.length !== 0){
this.onDeleteHistory(this.ExistingHistory.id);
this.historyService.addHistory(history).subscribe(
()=>{console.log("Success !");
this.Histories$=this.historyService.getHistory();},
()=>{console.log("error")}
);
}else{
this.historyService.addHistory(history).subscribe(
()=>{console.log("Success !");
this.Histories$=this.historyService.getHistory();},
()=>{console.log("error")}
);
}
}
);
}
But I get the following error, saying that it cannot read id of undefined :
The error basically says that ExistingHistory.id is undefined

JavaScript's Array.filter() returns a filtered array. You can't access this.ExistingHistory.id because this.ExistingHistory is an array, you would have to access it like so: this.ExistingHistory[0].id
If you want to get one value only then you should use Array.find():
this.ExistingHistory = response.find(x => x.id === history.id);
If there is a chance there is more than one duplicate, then you should use a .forEach loop:
this.ExistingHistory.forEach((x) => {
this.onDeleteHistory(x.id);
}
Do be warned however that you have a ton of nested subscriptions in that method, which is generally considered bad practice. I advise you to look into RXJS

Related

check for duplicate date from data and assign to new one json

i have a json which contain duplicate date , i want to merge duplicate date into single json object.
Data:
[
{"date":"2017-06-26","mac":"66"},
{"date":"2017-06-26","window":"400"},
{"date":"2017-07-03","mac":"19"},
{"date":"2017-07-03","window":"12"}
]
output should be:
[
{"date":"2017-06-26","mac":"66","window":"400"},
{"date":"2017-07-03","mac":"19","window":"12"}
]
Here a javascript function that does that, you can apply JSON.stringify(...) to the output after passing your array and obtain the new json.
(( a ) => {
// used to check for already inserted dates
let withoutDupes = { };
if(Array.isArray(a)) {
a.forEach( (item) => {
// assuming item has a "date" property inside
if(withoutDupes[item.date]) {
withoutDupes[item.date] = Object.assign( item, withoutDupes[item.date] );
} else {
withoutDupes[item.date] = item;
}
} );
}
return Object.values( withoutDupes );
})( a )
You can try using jq command line parser and its group_by function:
jq '[group_by(.date)|.[]|add]' file
[
{
"date": "2017-06-26",
"mac": "66",
"window": "400"
},
{
"date": "2017-07-03",
"mac": "19",
"window": "12"
}
]

Not able to fetch the value of a key from JSON data

I am trying to fetch value if "id" from JSON response I got from a POST request.
{
"callId": "87e90efd-eefb-456a-b77e-9cce2ed6e837",
"commandId": "NONE",
"content": [
{
"scenarioId": "SCENARIO-1",
"Channel": "Channel1-1",
"data": {
"section": {
"class": {
"repository": [
{
"export": "export-1",
"modules": "module-1",
"index": "23",
"period": {
"axis": {
"new_channel": "channel-1.1"
},
"points": [
{
"id": "6a5474cf-1a24-4e28-b9c7-6b570443df9c",
"duration": "150",
"v": 1.01,
"isNegligible": false
}
]
}
}
]
}
}
}
}
]
}
I am able to display the entire response json and am also able to get the value of "callId" using below code. Getting error at last line:
Cannot read property '0' of undefined
Code snippet:
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
let responseData = JSON.stringify(body);
//Display the entire response
console.log(responseData);
//Display the callId
console.log(body['callId']);
//Getting error here
console.log(body.content[0].repository[0].points[0].id);
}
}
Any solution to get value of "id" ?
Right now you are trying to log body.content[0].repository[0].points[0].id).
If you look at it carefully the repository[0] is an object and it has no immediate child points.
So repository[0].points would evaluate to undefined and by specifying repository[0].points[0], you are trying to access property 0 of undefined as the error states.
The correct way of accessing id would be as follows :
body.content[0].data.section.class.repository[0].period.points[0].id
If you have confusion regarding parsing JSON try breaking it down by consoling body and then by expanding it in the console or in JSONeditor
PS: It is also recommended that you check at each level if the value exists before trying to access a deeper child elements, since in some cases your body may not contain one of the values, say content for example. In that case trying to access body.content[0] will cause an error. So it is recommended to do checks at each level like follows
if(body){
if(body.content){
if(body.content[0]){
/* and so on*/
}
}
}
Try with
console.log(body.content[0].data.section.class.repository[0].period.points[0].id)

Nested JSON with objects and arrays, find value

Im building a React app and I have a quite complex JSON file where I need to find and output certain values of an object in an array.
Im trying to output all my people from my JSON, they look something like this:
people: [
{
"id": 1,
"email": "Sincere#april.biz",
"address": [
{
"street": "Kulas Light",
"type": "house",
"attribute": {
"sketch": "sketch.jpg",
"photo": "photo.jpg"
}
},
{
"street": "Lorem Ipsum",
"type": "apartment",
"attribute": {
"sketch": "sketch.jpg",
"photo": "photo.jpg"
}
}
]
}
]
I have no problem to output the email, doing it like so:
var App = React.createClass({
getInitialState: function () {
return {
results: {}
}
},
componentDidMount() {
fetch(REQUEST_URL) // fetch from API, returns JSON
.then(res => res.json())
.then(data => {this.setState(
{ results: data.people}
);
})
},
renderResult : function(key){
return <Result key={key} index={key} details={this.state.results[key]}/>
},
render : function() {
return (
<ul>
{Object.keys(this.state.results).map(this.renderResult)}
</ul>
)
}
});
var Result = React.createClass({
render : function() {
return (
<li>
{this.props.details.email}
<img src="{this.props.details.address.type=house.attribute.photo}"/>
</li>
)
}
});
ReactDOM.render(App, document.querySelector('#app'));
However, now I need to output "photo" but only for "type": "house". I tried this but no luck, well aware that this is way off. Im quite new to handling JSON data and React and Google hasn't helped me even after a few hours of trying to solve this.
The .address property isn't an object but an array of objects so
.type is not available directly on .address:
this.state.results.people.address.type
// .type property doesn't exist on array
Solution:
You can use Array.prototype.filter on .address to obtain an array of objects that have a property type whose value is "house":
var houseAddresses = this.state.results.people.address.filter(function(value){
return value.type === "house";
});
Here, houseAddress will be an array of objects whose type value is 'house".
You can then loop through the array to create the relevant JSX using for, Array#forEach or Array#map. The following example uses Array#map:
const houseImgTags = houseAddresses.map(function(house, index){
return (
<img
src={house.attribute.photo}
key={'house'+index}
/>
);
});
(A key was added here in case there are more than one instance of a house object)
You can simply write.
<img src={this.states.results.address.type==="house"?house.attribute.photo : otherwise_photo}/>
Basically this would compare address.type is house or not,then return the result corresponded.

How to get array number with groovy script in SoapUI?

I want to assert the value of a property in Json response with the use of Groovy script in SoapUI. I know a value for name but I need to know on which position the id is.
json response example:
{
"names":[
{
"id":1,
"name":"Ted"
},
{
"id":2,
"name":"Ray"
},
{
"id":3,
"name":"Kev"
}
]
}
Let's say I know that there is a name Ray, I want the position and the id (names[1].id)
Here is the script to find the same:
import groovy.json.*
//Using the fixed json to explain how you can retrive the data
//Of couse, you can also use dynamic value that you get
def response = '''{"names": [ { "id": 1, "name": "Ted", }, { "id": 2, "name": "Ray", }, { "id": 3, "name": "Kev", } ]}'''
//Parse the json string and get the names
def names = new JsonSlurper().parseText(response).names
//retrive the id value when name is Ray
def rayId = names.find{it.name == 'Ray'}.id
log.info "Id of Ray is : ${rayId}"
//Another way to get both position and id
names.eachWithIndex { element, index ->
if (element.name == 'Ray') {
log.info "Position : $index, And Id is : ${element.id}"
}
}
You can see here the output

Getting key and value from JSON with angular2

I am looking for best solution how to work with JSON in my angular2 app.
My JSON is:
{
"rightUpperLogoId": {
"id": 100000,
"value": ""
},
"navbarBackgroundColorIdCss": {
"id": 100001,
"value": ""
},
"backgroundColorIdCss": {
"id": 100002,
"value": ""
},
"translationIdFrom": {
"value": "90000"
},
"translationIdTo": {
"value": "90055"
}
}
This JSON is something like configuration file for UI of app. In my application, I want to get id from rightUpperLogoId, it is 100000. With this id I need to do GET task on my backend REST api and the returned value I would like to set to value. Thank you
You could leverage Rx operators like the flatMap one with Observable.forkJoin / Observable.of.
Here is a sample:
this.http.get('config.json')
.map(res => res.json())
.flatMap(config => {
return Observable.forkJoin(
Observable.of(config),
// For example for the request. You can build the
// request like you want
this.http.get(
`http://.../${config.rightUpperLogoId.id}`)
);
})
.map(res => {
let config = res[0];
let rightUpperLogoIdValue = res[1].json();
config.rightUpperLogoId.value = rightUpperLogoIdValue;
return config;
})
.subcribe(config => {
// handle the config object
});
This article could give you more hints (section "Aggregating data"):
http://restlet.com/blog/2016/04/12/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-2/