Add JSON data fields names Angular - json

I have data with no field names, I would like to append to each row a field name
[
"James Vega",
"23",
"abc#test.com"
],
I want to add the fields to this JSON data, I'm working on Angular 6
[
{ "name": "James Vega" },
{ "Age": 23 },
{ "email": "abc#test.com" }
],

You just use map function to transform the object you want
let arr=
[
[
"James Vega",
"23",
"abc#test.com"
]
];
let arr_transform=arr.map(el=> ({
name:el[0],
age:el[1],
email:el[2]
}));
console.log(arr_transform)

If your order of property would be the same, then it is possible to create a mapping and map it with O(1):
const foo = [
"James Vega",
"23",
"abc#test.com"
];
const mapping = {0: 'name', 1: 'Age', 2: 'email'};
const result = foo.map((el, i) => ({[mapping[i]]: el}));
console.log(result);

Related

How do i acess/map the name field of cities array inside the cities array in following json in dart/flutter

{
"cities": [
{
"cities": [
{
"name": "Adilabad",
},
{
"name": "Afjalpur",
},
]
},]
}
I am using Bloc pattern and trying to load the data in sugestions of SearchField.
I can access cities array like this -> state.cities.map((e) => e.city).toList();
but how can i access the name inside the array
You can do the following to get the city name.
Map map = {
"cities": [
{
"cities": [
{
"name": "Adilabad",
},
{
"name": "Afjalpur",
},
]
},
]
}; //´´
final cities = map['cities'][0]['cities'];
print(map['cities'][0]['cities']); // [{name: Adilabad}, {name: Afjalpur}]
print(cities[0]['name']); // Adilabad

Reactjs - How to create a JSON with list Child Object?

I have JSON structure like this
"timebought": "2021-01-01T00:00:00",
"totalCost": 3000.0,
"address": "ABC",
"status": false,
"customersEmail":"nguyenvana#gmail.com",
"orderDetails": [
{
"productId": "A1",
"amount": 5
},
{
"productId": "A2",
"amount": 5
}
]
If I want make a JSON for post, how do i do it? I mean the child object "orderDetails", can you give me an example?
I found out how to do it:
First, make a function return list Child:
function toArr(){
let arr = [];
prodList.forEach((prod) => {
let item ={"id":prod.id,"amount" : prod.quantity};
arr = [...arr,item];
});
console.log(arr);
return arr;}
and then
const body = JSON.stringify({
customersEmail : e.target.email.value,
totalCost : totalCost.current,
status : false,
address: e.target.address.value,
orderDetails: toArr()
});

react native json image

I want to print out JSON images as a variable.
This is my local JSON file (JsonData.json):
{
"appetizer": [
{
"num": "appetizer1",
"name": "salad",
"condition": [ "1", "2" ],
"image": "./appetizer/salad.png"
},
{
"num": "appetizer2",
"name": "soup",
"condition": [ "2", "3" ],
"image": "./appetizer/soup.png"
},
…
],
"main": [
{
"num": "main1",
"name": "beef",
"condition": [ "1" ],
"image": "./main/beef.png"
},
{
"num": "main2",
"name": "fish",
"condition": [ "2", "3" ],
"image": "./main/fish.png"
},
…
]
}
I filtered the name when condition="2". (salad,soup,fish)
This is the code for filtering name:
const newArray1 = [...JsonData["apptizer"], ...JsonData["main"]];
const JsonResult = newArray1.filter(item => {
if(item.condition.indexOf("2") !== -1) return item.name;
});
AND I want to get the image when condition="2".
How can I get them? And How can I print out them?
Do I have to use base64? If so, Can you tell me how to use it?
I saw the explanation, but I can't understand it.
And I imported JSON file this way (I've been correctly using it):
var JsonData = require('./JsonData.json');
You can use below code:
let mainObject = JSON.parse(JSON.stringify(data))
let allKeys = Object.keys(mainObject)
let finalObject = []
allKeys.map((value, index) => {
let array = mainObject[value]
array.map((aryObject, aryIndex) => {
let condition = aryObject['condition']
if (condition.includes('2')) {
finalObject.push(aryObject)
}
})
})
alert(JSON.stringify(finalObject))
You can import data in top of screen:
import { data } from './data';
You can add below text in data.js:
export const data = {
"appetizer": [
{
"num": "appetizer1",
"name": "salad",
"condition": ["1"],
"image": "./appetizer/salad.png"
},
{
"num": "appetizer2222",
"name": "soup",
"condition": ["2", "3"],
"image": "./appetizer/soup.png"
},
],
"main": [
{
"num": "main1",
"name": "beef",
"condition": ["1"],
"image": "./main/beef.png"
},
{
"num": "main2",
"name": "fish",
"condition": ["21", "3"],
"image": "./main/fish.png"
},
]
}
You can use Object#values to get the arrays corresponding to appetizer and main and then Array#flat to extract the nested objects into a transformed array. Then use the Array#filter (which you are already using) to filter out only the required objects based on your condition and then Array#map to get the name and image values out of every filtered object into an array of objects.
Please consider following snippts
const jsonData = {"appetizer":[{"num":"appetizer1","name":"salad","condition":["1","2"],"image":"./appetizer/salad.png"},{"num":"appetizer2","name":"soup","condition":["2","3"],"image":"./appetizer/soup.png"}],"main":[{"num":"main1","name":"beef","condition":["1"],"image":"./main/beef.png"},{"num":"main2","name":"fish","condition":["2","3"],"image":"./main/fish.png"}]};
const filteredValues = Object.values(jsonData)
.flat()
.filter(o => o.condition.includes('2'))
.map(({name, image}) => ({ name, image }));
console.log(filteredValues);
The output of the above code will be an array of objects having the following structure
[{
"name": SOME_NAME,
"image": SOME_PATH
},
{
"name": SOME_NAME,
"image": SOME_PATH
},
...
]
You can use the above array to retrieve your image path and display it accordingly.
I think you shouldn't be worried about base64 as images are stored locally and path will be sufficient to display the image.
Hope this will help!!!
Side Note: You can avoid the Array#flat part as you are already doing it manually [...JsonData["apptizer"], ...JsonData["main"]] but flat will be handy in case there are more keys in jsonData that need to be considered.

How to split one Json to Multiple Json using Angular 2/lodash

I have a json and i want to split each key value pair to new json object.
Input:
tokenData = [{
"firstname" : "Priya",
"from": "21-09-2001",
"to": "22-08-2001",
"address": "zczxczxczx"
}]
Expected Result:
tokenItems = [
{"firstname" : "Priya"},
{"from": "21-09-2001"},
{"to": "22-08-2001"},
{"address": "zczxczxczx"}
];
You can achieve to that result without lodash.
Use Object.entries, get the key/values and then use map function to create your desired structure of objects.
const tokenData = [{
"firstname" : "Priya",
"from": "21-09-2001",
"to": "22-08-2001",
"address": "zczxczxczx"
}];
const newTokenData = Object.entries(tokenData[0])
.map(([key, val]) => ({ [key]: val }));
console.log(newTokenData);
Why use lodash, Simply you can get this using plan javascript, you need to iterate over the key/value pair for each object like this -
const tokenData = [{
"firstname" : "Priya",
"from": "21-09-2001",
"to": "22-08-2001",
"address": "zczxczxczx"
}];
let newArr = []
for (let a in tokenData[0]){
newArr.push({[a]: tokenData[0][a]});
}
console.log(newArr);

How to Check a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this.
{
"resultset": {
"violations": {
"hpd": [
{
"0": {
"ViolationID": "110971",
"BuildingID": "775548",
"RegistrationID": "500590",
"Boro": "STATEN ISLAND",
"HouseNumber": "275",
"LowHouseNumber": "275",
"HighHouseNumber": "275",
"StreetName": "RICHMOND AVENUE",
"StreetCode": "44750",
"Zip": "10302",
"Apartment": "",
"Story": "All Stories ",
"Block": "1036",
"Lot": "1",
"Class": "A",
"InspectionDate": "1997-04-11",
"OriginalCertifyByDate": "1997-08-15",
"OriginalCorrectByDate": "1997-08-08",
"NewCertifyByDate": "",
"NewCorrectByDate": "",
"CertifiedDate": "",
"OrderNumber": "772",
"NOVID": "3370",
"NOVDescription": "§ 27-2098 ADM CODE FILE WITH THIS DEPARTMENT A REGISTRATION STATEMENT FOR BUILDING. ",
"NOVIssuedDate": "1997-04-22",
"CurrentStatus": "VIOLATION CLOSED",
"CurrentStatusDate": "2015-03-10"
},
"count": "1"
}
]
}
},
"count": "1",
"total_page": 1,
"current_page": 1,
"limit": [
"0",
"1000"
],
"status": "success",
"error_code": "",
"message": ""
}
I am trying to test whether my response body has "ViolationID":"110971".
I tried the below code in postman:
var jsonData =JSON.parse(responseBody);
tests["Getting Violation Id"] = jsonData.resultset.violations.hpd[0].ViolationID === 110971;
Two issues I noticed in the provided data. The following suggestions might help you:
Add missing closing braces at the end.
Add missing 0 in the index like this: resultset.violations.hpd[0].0.ViolationID
If the hpd array always contains only 1 member, the test might be pretty straightforward:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationId = jsonBody.resultset.violations.hpd[0]["0"].ViolationID;
pm.expect(parseInt(violationId)).to.eql(110971);
})
However, if hpd array might contain more than one member, it gets a bit trickier. I would suggest mapping only ViolationID keys from nested objects:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationIds = jsonBody.resultset.violations.hpd.map(hpd => hpd["0"].ViolationID);
pm.expect(violationIds).to.contain('110971');
})