how to get the value of Json? - javascript

I want to get the key and value from JSON data like below.
{
"data": {
"listCard": {
"cards": [
{
"id": "2",
"title": "벗꽃볼사람",
"content": "하이",
"createdAt": "2019-04-17T16:06:31.962772+00:00",
"creator": {
"id": "2",
"name": "운영자"
}
},
{
"id": "1",
"title": "벗꽃볼사람",
"content": "하이",
"createdAt": "2019-04-17T16:06:14.789277+00:00",
"creator": {
"id": "2",
"name": "운영자"
}
}
]
}
}
}
i use console.log(data.listCard)
it shows below
{cards: Array(2), __typename: "ListCardResponse"}
cards: Array(2)
0: {id: "2", createdAt: "2019-04-17T16:06:31.962772+00:00", updatedAt: "2019-04-17T16:06:31.962820+00:00", title: "벗꽃볼사람", content: "하이", …}
1: {id: "1", createdAt: "2019-04-17T16:06:14.789277+00:00", updatedAt: "2019-04-17T16:06:14.789315+00:00", title: "벗꽃볼사람", content: "하이", …}
length: 2
__proto__: Array(0)
__typename: "ListCardResponse"
__proto__: Object
but i use console.log(data.listCard.cards)
it show cards is not define.
finally i want to use data.listCard.cards.map.
could you help me?

Firstly, it's not JSON - it's an ordinary JavaScript object. Secondly, using object.data.listCard.cards works perfectly:
const object = {
"data": {
"listCard": {
"cards": [{
"id": "2",
"title": "벗꽃볼사람",
"content": "하이",
"createdAt": "2019-04-17T16:06:31.962772+00:00",
"creator": {
"id": "2",
"name": "운영자"
}
},
{
"id": "1",
"title": "벗꽃볼사람",
"content": "하이",
"createdAt": "2019-04-17T16:06:14.789277+00:00",
"creator": {
"id": "2",
"name": "운영자"
}
}
]
}
}
};
console.log(object.data.listCard.cards);
.as-console-wrapper { max-height: 100% !important; top: auto; }

Since you wanted to use .map(). We iterate through d.data.listCard.cards. But you might want to consider using forEach.
Documentation: Map
Access the object data.listCard.cards.map or data['listCard']['cards']. Using bracket notation or dot notation.
Documentation: Property Accessors
let d = {
"data": {
"listCard": {
"cards": [
{
"id": "2",
"title": "벗꽃볼사람",
"content": "하이",
"createdAt": "2019-04-17T16:06:31.962772+00:00",
"creator": {
"id": "2",
"name": "운영자"
}
},
{
"id": "1",
"title": "벗꽃볼사람",
"content": "하이",
"createdAt": "2019-04-17T16:06:14.789277+00:00",
"creator": {
"id": "2",
"name": "운영자"
}
}
]
}
}
}
// Map
// Or d['data']['listCard']['cards']
d.data.listCard.cards.map(v => {
console.log(v)
});
// forEach
// Or d.data['listCard']['cards']
d.data.listCard.cards.forEach(v => {
console.log(v)
});
I use map when I need to return a new array or object.
// Map Returns Array
let data = d.data.listCard.cards.map(v => v);
console.log(data);

Related

how to update in nested array in MongoDB

I'm trying to update seat_status but i'm new to Mongodb I try to use aggregate function but it's not modifying original document then I try $ operator but not worked as i expected this is my collection.......................................................................................................................................................................................
{
"_id": {
"$oid": "62b0c3342f155a7ad94cc81c"
},
"totalShowByDay": "2",
"totalShowDays": 4,
"movieId": {
"$oid": "62b04c782828dd04f0d1c1ad"
},
"screenId": {
"$oid": "62b04b8e2828dd04f0d1c1ac"
},
"createdAt": 1655751476553,
"showId": {
"$oid": "62b0c3342f155a7ad94cc6db"
},
"show_seats": [{
"showByDate": {
"ShowDate": "2022-06-20",
"shows": [{
"showTime": "2022-06-20T10:00",
"showSeats": [{
"_id": {
"$oid": "62b0c3342f155a7ad94cc6dc"
},
"seat_number": "1",
"tag_name": "A",
"seat_status": false,
"user_id": false,
"price": "110",
"seats_category": "CLASSIC",
"show_time": "2022-06-20T10:00"
}, {
"_id": {
"$oid": "62b0c3342f155a7ad94cc6dd"
},
"seat_number": "2",
"tag_name": "A",
"seat_status": false,
"user_id": false,
"price": "110",
"seats_category": "CLASSIC",
"show_time": "2022-06-20T10:00"
this is the code i try to modify......................................................................................................................................................
db.seats.updateOne({"show_seats.$.showByDate.shows.$.showSeats.$._id:ObjectId("62b0c3342f155a7ad94cc81c")},{$set:{"show_seats.$.showByDate.shows.$.showSeats.$.seat_status":1}})

How to correctly use JSON.parse()? JSON result is not valid

When I use JSON.parse(myJSONString) the result is not a valid JSON file. I'm in an nodejs environment. Any Ideas what I can fix in my code? I user XML2JS to converte an XML Api call to JS.
I have printed out the results and already dived deeper into JSON.parse but didn't find further information...
exports.getStations = functions.https.onCall(async (data) => {
let stations
await axios.get(encodeURI(`XMLAPi`))
.then(async (response) => {
parseString(response.data, (err, result) => {
stations = JSON.stringify(result)
console.log(stations) //First console.log
})
})
.catch((error) => {
console.log(error)
})
console.log(JSON.parse(stations)) //Second console.log
return JSON.parse(stations)
})
Result for first console.log (valid JSON but String):
{"itdRequest":{"$":{"xsi:noNamespaceSchemaLocation":"itd.xsd","language":"DE","sessionID":"EfaOpenServiceT_2882840828","client":"axios/0.19.0","serverID":"EfaOpenServiceT_","clientIP":"127.0.0.1","version":"10.3.5.46","virtDir":"static02","xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance"},"itdStopFinderRequest":{"$":{"requestID":"1"},"itdOdv":{"$":{"type":"any","usage":"sf","anyObjFilter":"42"},"itdOdvPlace":{"$":{"state":"empty"},"odvPlaceElem":""},"itdOdvName":{"$":{"state":"list"},"itdMessage":{"$":{"type":"error","module":"BROKER","code":"-8011"}},"odvNameElem":[{"_":"Mettmann, Stadtwald S","$":{"value":"0:1","selected":"1","listIndex":"0","streetName":"","omc":"5158024","placeID":"5","x":"6987248.99348","y":"51250980.94198","mapName":"WGS84","id":"20019083","anyType":"stop","anyTypeSort":"2","nameKey":"","locality":"Mettmann","postCode":"","objectName":"Stadtwald S","buildingName":"","buildingNumber":"","matchQuality":"235","stateless":"20019083"}},{"_":"Mettmann, ME-Zentrum S","$":{"value":"1:2","selected":"0","listIndex":"1","streetName":"","omc":"5158024","placeID":"5","x":"6979002.45917","y":"51249372.83702","mapName":"WGS84","id":"20019020","anyType":"stop","anyTypeSort":"2","nameKey":"","locality":"Mettmann","postCode":"","objectName":"ME-Zentrum S","buildingName":"","buildingNumber":"","matchQuality":"234","stateless":"20019020"}},{"_":"Mettmann, Neanderthal S","$":{"value":"2:3","selected":"0","listIndex":"2","streetName":"","omc":"5158024","placeID":"5","x":"6953346.57466","y":"51227837.93128","mapName":"WGS84","id":"20019191","anyType":"stop","anyTypeSort":"2","nameKey":"","locality":"Mettmann","postCode":"","objectName":"Neanderthal S","buildingName":"","buildingNumber":"","matchQuality":"234","stateless":"20019191"}}],"odvNameInput":"mettmann"},"genAttrList":{"genAttrElem":[{"name":"anyObjFilter","value":"STOP"},{"name":"anyObjFilter","value":"ADDRESS"},{"name":"anyObjFilter","value":"POI"}]}},"itdDateTime":{"$":{"ttpFrom":"20190601","ttpTo":"20191231"},"itdDate":{"$":{"day":"10","month":"8","year":"2019","weekday":"7"}},"itdTime":{"$":{"hour":"16","minute":"4"}}}}}}
Result for second console.log (invalid JSON after parse):
Object {
"data": Object {
"itdRequest": Object {
"$": Object {
"client": "axios/0.19.0",
"clientIP": "127.0.0.1",
"language": "DE",
"serverID": "EfaOpenServiceT_",
"sessionID": "EfaOpenServiceT_2882840828",
"version": "10.3.5.46",
"virtDir": "static02",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:noNamespaceSchemaLocation": "itd.xsd",
},
"itdStopFinderRequest": Object {
"$": Object {
"requestID": "1",
},
"itdDateTime": Object {
"$": Object {
"ttpFrom": "20190601",
"ttpTo": "20191231",
},
"itdDate": Object {
"$": Object {
"day": "10",
"month": "8",
"weekday": "7",
"year": "2019",
},
},
"itdTime": Object {
"$": Object {
"hour": "16",
"minute": "4",
},
},
},
"itdOdv": Object {
"$": Object {
"anyObjFilter": "42",
"type": "any",
"usage": "sf",
},
"genAttrList": Object {
"genAttrElem": Array [
Object {
"name": "anyObjFilter",
"value": "STOP",
},
Object {
"name": "anyObjFilter",
"value": "ADDRESS",
},
Object {
"name": "anyObjFilter",
"value": "POI",
},
],
},
"itdOdvName": Object {
"$": Object {
"state": "list",
},
"itdMessage": Object {
"$": Object {
"code": "-8011",
"module": "BROKER",
"type": "error",
},
},
"odvNameElem": Array [
Object {
"$": Object {
"anyType": "stop",
"anyTypeSort": "2",
"buildingName": "",
"buildingNumber": "",
"id": "20019083",
"listIndex": "0",
"locality": "Mettmann",
"mapName": "WGS84",
"matchQuality": "235",
"nameKey": "",
"objectName": "Stadtwald S",
"omc": "5158024",
"placeID": "5",
"postCode": "",
"selected": "1",
"stateless": "20019083",
"streetName": "",
"value": "0:1",
"x": "6987248.99348",
"y": "51250980.94198",
},
"_": "Mettmann, Stadtwald S",
},
Object {
"$": Object {
"anyType": "stop",
"anyTypeSort": "2",
"buildingName": "",
"buildingNumber": "",
"id": "20019020",
"listIndex": "1",
"locality": "Mettmann",
"mapName": "WGS84",
"matchQuality": "234",
"nameKey": "",
"objectName": "ME-Zentrum S",
"omc": "5158024",
"placeID": "5",
"postCode": "",
"selected": "0",
"stateless": "20019020",
"streetName": "",
"value": "1:2",
"x": "6979002.45917",
"y": "51249372.83702",
},
"_": "Mettmann, ME-Zentrum S",
},
Object {
"$": Object {
"anyType": "stop",
"anyTypeSort": "2",
"buildingName": "",
"buildingNumber": "",
"id": "20019191",
"listIndex": "2",
"locality": "Mettmann",
"mapName": "WGS84",
"matchQuality": "234",
"nameKey": "",
"objectName": "Neanderthal S",
"omc": "5158024",
"placeID": "5",
"postCode": "",
"selected": "0",
"stateless": "20019191",
"streetName": "",
"value": "2:3",
"x": "6953346.57466",
"y": "51227837.93128",
},
"_": "Mettmann, Neanderthal S",
},
],
"odvNameInput": "mettmann",
},
"itdOdvPlace": Object {
"$": Object {
"state": "empty",
},
"odvPlaceElem": "",
},
},
},
},
},
}
You are already converting to string as a parsestring function. But it's also converting to JSON.stringify().
You can try check this value
let stations = await axios.get(encodeURI(`XMLAPi`));
console.log(JSON.stringify(stations.data)) // What is value??

Normalising JSON data

{
"id": "123",
"author": {
"id": "1",
"name": "Paul"
},
"title": "My awesome blog post",
"comments": [
{
"id": "324",
"commenter": {
"id": "2",
"name": "Nicole"
}
}
]
}
This is JSON for an article
{
result: "123",
entities: {
"articles": {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: [ "324" ]
}
},
"users": {
"1": { "id": "1", "name": "Paul" },
"2": { "id": "2", "name": "Nicole" }
},
"comments": {
"324": { id: "324", "commenter": "2" }
}
}
}
Im currently looking through redux tutorials, they give a helper which normalise JSON data, does anyone know what type of normalisation this is?

Changing arrays using map in javascript

This is my json object:
{
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
}
I want my output like this:
{
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"cats": [1,2] // this 1 and 2 is coming from categoriesservices array inside the category object i have id
}
How to do this using map function? I am new to javascript, which is good approach map or forloop?
See destructuring assignment, Array.prototype.map(), and JSON for more info.
// Input.
const input = {
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
}
// Categories => Objects to Cats => Ids.
const output = (input) => JSON.parse(JSON.stringify({
...input,
cats: input.categoryservices.map(({category: {id}}) => id),
categoryservices: undefined
}))
// Log.
console.log(output(input))
If you are not worried about original object immutability, then try this
obj['cats'] = obj['categoryservices'].map(cat => cat.category.id);
delete obj['categoryservices'];
console.log(obj);
I just use .map() on categoryservices array:
var output = {
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
};
output.cats = output.categoryservices.map((element) =>
element.category.id);
delete output.categoryservices;
console.log(JSON.stringify(output));
use .map() , it return value as array ! You want to change is categoryservices key only ! So delete that after you get wanted value ..
var output = {
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
};
output.cats = output.categoryservices.map(i => i.category.id );
delete output.categoryservices;
console.log(output);
Try this working demo :
var jsonObj = {
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
};
var arr = jsonObj.categoryservices.map(item => item.category.id)
jsonObj.cats = arr;
delete jsonObj.categoryservices;
console.log(jsonObj);
Try this
var testData={
"id": 2,
"service": "mobile",
"min": "20",
"per": "10",
"tax": "1",
"categoryservices": [
{
"category": {
"id": 1,
"name": "laptop"
}
},
{
"category": {
"id": 2,
"name": "software"
}
}
]
}
testData.cats=[];
testData.categoryservices.forEach(function (item) {
testData.cats.push(item.category.id);
});
delete testData.categoryservices;
console.log(testData);
You can try using jquery each:
<div id="log"></div>
var conversation = {
'John': {
1: 'Test message 1',
2: 'Test message 2',
'Reply': {
3: 'Test message 3',
4: 'Test message 4'
}
},
'Jack': {
5: 'Test message 5',
6: 'Test message 6'
}
};
function iterate(obj) {
if (typeof obj === 'string') {
$('#log').append((obj + '<br/>'));
}
if (typeof obj === 'object') {
$.each(obj, function(key, value) {
iterate(value);
});
}
}
iterate(conversation);

lodash create new json object from existing one

I want to delete and rename some props of my existing JSON Object to use it with select2/select2 query plugins
My JSON object that i need to transform is:
[
{
"id": 1,
"type": "Subject1",
"createdAt": "2016-02-19T23:03:12.000Z",
"updatedAt": "2016-02-19T23:03:12.000Z",
"Tags": [
{
"id": 1,
"name": "sub1",
"createdAt": "2016-02-19T23:03:12.000Z",
"updatedAt": "2016-02-19T23:03:12.000Z",
"tagType": 1
}
]
},
{
"id": 2,
"type": "Subject2",
"createdAt": "2016-02-19T23:03:12.000Z",
"updatedAt": "2016-02-19T23:03:12.000Z",
"Tags": [
{
"id": 16,
"name": "sub2",
"createdAt": "2016-02-19T23:03:12.000Z",
"updatedAt": "2016-02-19T23:03:12.000Z",
"tagType": 2
}
]
},
{
"id": 3,
"type": "Subject3",
"createdAt": "2016-02-19T23:03:12.000Z",
"updatedAt": "2016-02-19T23:03:12.000Z",
"Tags": [
{
"id": 22,
"name": "sub3",
"createdAt": "2016-02-19T23:03:12.000Z",
"updatedAt": "2016-02-19T23:03:12.000Z",
"tagType": 3
}
]
}
]
To
[
{
"text": "Subject1",
"children": [
{
"id": 1,
"text": "sub1"
}
]
},
{
"text": "Subject2",
"children": [
{
"id": 16,
"text": "sub2"
}
]
},
{
"text": "Subject3",
"children": [
{
"id": 22,
"text": "sub3"
}
]
}
]
I need to :
rename name and type to text
delete tagType, updatedAt and createdAt
rename Tags to children
remove the id of each top objects
Is there a way to do all this using lodash ?
What the best way?
var res = _.map(items, function(item){
return {
text: item.type,
children: _.map(item.Tags, function(tag){
return {
id: tag.id,
text: tag.name
};
})
};
});
I succed using this link by nesting two return :
Creating new javascript Object form existing one
var result = tags.map(function(obj) {
return {
text: obj.type,
childrens:obj.Tags.map(function(obj) {
return {
id : obj.id,
text : obj.name
}
})
};
});

Categories