How to dynamically add object inside json array? - json

I'm trying to dynamically add an object inside every object which is present in my json array. But I'm unable to do so. My object is getting appended at the end of json which is not what I want.
jsonArray:any=[
{
"id": 1000,
"body": "some comment",
"postId": 1
},
{
"id": 2,
"body": "some comment",
"postId": 1
},
{
"id": 3,
"body": "some comment",
"postId": 1
}
]
selectFLag:any={"selected":"true"}
temArray:any;
learnJSONPArse()
{
for (var i = 0; this.jsonArray.length > i; i++)
{
Alert(this.jsonArray.length)
}
}
this.jsonArray.push(this.selectFLag)
-----expected output is
[
{
"id": 1000,
"body": "some comment",
"postId": 1,
"selected":"true"
},
{
"id": 2,
"body": "some comment",
"postId": 1,
"selected":"true"
},
{
"id": 3,
"body": "some comment",
"postId": 1,
"selected":"true"
}
]

You're question is a little unclear, but it sounds like you want to map each item in your array to a new item. The new item is the same as the old one, but assigned an additional property.
If so, something like this could work for you:
const objToAppend = { selected: true };
jsonArray.map(item => Object.assign(item, objToAppend));
Refs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Related

Postman accessing child objects in Json in a Test

I am trying to access the name object in this Json to put in a local variable in a Postman Test.
Json
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75.00,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
I am using this code to loop through the Line Array but if I try and go deeper than 1 level Itemref it returns undefined
let ProductArray=[];
for (let i=0; i < Line.length; i++) {
//
ProductArray.push({
"value":Line[i].SalesItemLineDetail.ItemRef.name
})
}
I have also tried
'"value":Line[i].SalesItemLineDetail["ItemRef"].name
"value":Line[i].SalesItemLineDetail["ItemRef"]["name"]
all return ItemRef undefined
What is the correct syntax or code?
TIA
There are just some small pieces missing with your code. I re-create a test and mocked the same JSON data. I just add the missing pieces to your code and the test was Successful.
GET Request:
//Response body JSON
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
// Tests
// Check response body
const res = pm.response.json().Line;
let ProductArray=[];
for (let i=0; i < res.length; i++) {
const res = pm.response.json().Line;
ProductArray.push({
"value":res[i].SalesItemLineDetail.ItemRef.name
})
// Lets see console.log result
console.log('Check For:', res[i].SalesItemLineDetail.ItemRef.name)
// Set Result to environment variables
pm.environment.set("variable_key", res[i].SalesItemLineDetail.ItemRef.name);
}
console.log output: Design which is also added to environment variables.

In AngularJS, Adding field to Array from another json file, possible callback issue

AngularJS Service:
Get json sub-record field for import into current open array record.
I have one json file with "services" in it (id, name) services.json,
I need to forEach through them, but as I am in each service I need to open sub-record(welding.json) and grab a field(title) and add it to the current record.
NOTE: My project is a CLI type.
services.json
[
{
"id": 1,
"name": "welding"
},
{
"id": 2,
"name": "carpentry"
},
{
"id": 3,
"name": "mechanic"
}
]
= Sub-Records =
welding.json
{
"category": "labor",
"title": "Arc Welding",
"description": "",
"experience": "20+ Years",
"details": ""
}
Expectation:
{
"id": 1,
"name": "welding",
"title": "Arc Welding"
}
Try this
angular.forEach($scope.services, function (value, key) {
if(value.name == 'welding'){
$http.get('welding.json').then(function (response) {
$scope.welding = response;
})
$scope.services.title=$scope.welding.title;
}});

Bootstrap Typeahead search issue with data contains HTML

I am facing issue with bootstrap typeahead with data contains HTML angular brackets. My data is like
var jsonData = [
{
"id": 1,
"name": "<Andrew> Pougher"
},
{
"id": 2,
"name": "Michele Moore"
},
{
"id": 3,
"name": "Michele Boob"
},
{
"id": 4,
"name": "Michael Moore"
},
{
"id": 5,
"name": "George Michael"
}
]
If I type "u" in input field, it will create tag in HTML and values search dropdown displayes with value like "Pougher" instead of < Andrew > Pougher

Render Nested json objects in React Native

In my render() method i need to parse nested json objects. See the portion of render and json structure below.
I access Last Name with {params.name_last}.
How will i access items under team, like team.name_first
render() {
let { params } = this.props.navigation.state
<Text>{params.name_last}</Text>
}
[
{
"id": 1,
"name_first": "Name first 1",
"name_middle": "",
"name_last": "Name last 1",
"name_suffix": "",
"phone": "888-8888",
"fax": "888-8888",
"updated_at": "2015-11-02T21:42:42.000Z",
"team": [
{
"id": 16,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 28,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 29,
"name_first": "aaa ",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
}
]
}
]
Since team is an array, you need to either access a specific entry in the array, or iterate over the entire thing.
To reach a specific property in the nested array entry (assuming you want the object at index i):
params.team[i].name_first
To create an array of first names:
params.team.map(x => x.name_first)

Search JSON for multiple values, not using a library

I'd like to be able to search the following JSON object for objects containing the key 'location' then get in return an array or json object with the 'name' of the person plus the value of location for that person.
Sample return:
var matchesFound = [{Tom Brady, New York}, {Donald Steven,Los Angeles}];
var fbData0 = {
"data": [
{
"id": "X999_Y999",
"location": "New York",
"from": {
"name": "Tom Brady", "id": "X12"
},
"message": "Looking forward to 2010!",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/X999/posts/Y999"
},
{
"name": "Like",
"link": "http://www.facebook.com/X999/posts/Y999"
}
],
"type": "status",
"created_time": "2010-08-02T21:27:44+0000",
"updated_time": "2010-08-02T21:27:44+0000"
},
{
"id": "X998_Y998",
"location": "Los Angeles",
"from": {
"name": "Donald Steven", "id": "X18"
},
"message": "Where's my contract?",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/X998/posts/Y998"
},
{
"name": "Like",
"link": "http://www.facebook.com/X998/posts/Y998"
}
],
"type": "status",
"created_time": "2010-08-02T21:27:44+0000",
"updated_time": "2010-08-02T21:27:44+0000"
}
]
};
#vsiege - you can use this javascript lib (http://www.defiantjs.com/) to search your JSON structure.
var fbData0 = {
...
},
res = JSON.search( fbData0, '//*[./location and ./from/name]' ),
str = '';
for (var i=0; i<res.length; i++) {
str += res[i].location +': '+ res[i].from.name +'<br/>';
}
document.getElementById('output').innerHTML = str;
Here is a working fiddle;
http://jsfiddle.net/hbi99/XhRLP/
DefiantJS extends the global object JSON with the method "search" and makes it possible to query JSON with XPath expressions (XPath is standardised query language). The method returns an array with the matches (empty array if none were found).
You can test XPath expressions by pasting your JSON here:
http://www.defiantjs.com/#xpath_evaluator