Getting undefined trying to get value of JSON - javascript

I'm getting undefined trying to access some key inside of my JSON. The issue is because my value is inside of an Array.
I'm using console.log(jsonTest.data.eventHeader.id)
I've tried to use console.log(jsonTest.data[].eventHeader.id)
JSON Structure:
{ "data": [ { "eventHeader": { "id": "value" } } ] }
NodeJs code:
return rp(dataQuery) // simple query
.then((responseQuery: string) => {
JSON.parse(responseQuery);
const jsonTest: any = JSON.parse(responseQuery);
console.log(jsonTest.data.eventHeader.id)
fs.writeFileSync('liferaft-properties', jsonTest.username);
return responseQuery;
});

console.log(jsonTest.data[0].eventHeader.id) worked fine

Related

make the query dynamically to change using sanity.io groq

Hi there I'm trying to make a post request where I want to update one field on sanity.io
this is my query
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
`rewardItem[_key == \"${key}\"].lastTimeReward`: "TEst",
},
}
but this won't let me even run my project,
its giving me this error on console.log: Unexpected token;
When I do my query like this, it works
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
"rewardItem[_key == \"e88959e43ce7\"].lastTimeReward": "Test",
},
}
}]
Thanks a lot.
Your set-property is an object, and you can't enter a dynamic key directly into the object. To do what you are trying to do here, you can wrap the dynamic key in square brackets like this. That should give you the output you desire
const variable = "example"
const a = { [`template ${variable}`]: "value" }
console.log(a)

Unable to access nested elements and to apply functions in Vue template?

I'm new to web development and I'm running into an issue I can't solve...
I'm using Vuejs, Express, MongoDB and Fetch API...
In my script I'm fetching data from my local server:
mounted() {
fetch("http://localhost:5000/api/" + this.$route.params.id)
.then((res) => res.json())
.then((data) => {
this.data = data
console.log(this.data.telegram.length)
})
.catch((err) => console.log(err.message))
}
console.log is working fine.
data is returned like that:
{ "_id": "6061ee831114fc4c211678e6", "path": "mypath", "telegram": [ { "date": "2021-03-21T22:00:00.708Z", "followers": 2188 }, { "date": "2021-03-22T18:40:04.751Z", "followers": 2195 } ], "__v": 0 }
Then data is stored as:
data() {
return {
data: []
}
}
First of all, I'm surprised by the format of my data. I believed it was going to appear as JavaScript Format, meaning without quotes (" ") on keys... I tried to JSON.parse the response but it returns an error like if it was already parsed. Is it normal ?
Also, in my template, I'm unable to access properties of this 'data'.
For example:
<p>{{data.telegram[0]}}</p>
or
<p>{{data.telegram.length}}</p>
is returning 'Uncaught (in promise) TypeError: Cannot read property '0' of undefined' and 'Uncaught (in promise) TypeError: Cannot read property 'length' of undefined'.
It seems there is something I have not quite understood...
Any help appreciated !
data.telegram is undefined until your mounted method get a response from the server. I suggest you to replace your template code with a computed property that check if your data has value:
<template>
<p>{{mydata}}</p>
<p>{{telegramLen}}</p>
</template>
<script>
export default {
computed: {
mydata() {
if (this.data != [])
return this.data.telegram[0]
return "No data"
},
telegramLen() {
if (this.data.length > 0)
return this.data.telegram.length
return 0
}
}
}
</script>

Filter Array Using Partial String Match in Javascript

I have an array of objects where the value I need to filter on is buried in a long string. Array looks like:
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
},
So if I wanted to grab all the partnerId objects where value includes parent_sku how would I do that?
console.log(data.value.includes('parent_sku') returns cannot read property 'includes' of null.
EDIT:
Didn't think this mattered, but judging by responses, seems it does. Here's the full response object:
Response body: {
"data": {
"configurationByCode": [
{
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
}
I'm passing that into a re-usable function for filtering arrays:
const parentSkuPartners = filterArray(res.body.data.configurationByCode, 'parent_sku');
Function:
function filterArray(array, filterList) {
const newList = [];
for (let i = 0; i < array.length; i += 1) {
console.log('LOG', array[i].data.value.includes('parent_sku');
}
}
The problem is somewhere else. The code you've tried should work to find if a value contains a string – I've added it the snippet below and you'll see it works.
The issue is how you are accessing data and data.value. The error message clearly states that it believes that data.value is null. We would need to see the code around it to be able to figure out what the problem is. Try just logging to console the value of data before you run the includes function.
const data = {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}", "partnerId": 1
};
console.log('includes?', data.value.includes('parent_sku'));
You can use data.value.includes('parent_sku') as you have suggested. The issue here is that your object is nested inside an unnamed object.
try:
"data": {
"value": "{\"cols\":[\"parent_sku\"],\"label\":\"Style\",\"description\":\"Enter Style.\",\"placeholderText\":\"Style 10110120103\"}",
"partnerId": 1
}
The problem was some of the values for value were null. Adding an extra conditional fixed it:
if (array[i].data.value !== null) {
Use lodash includes, and lodash filter like
let configurationByCode = [{
data: {
value: {
cols:["parent_sku"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 1
}
}, {
data: {
value: {
cols:["nothing"],
label:"Style",
description:"Enter Style.",
placeholderText:"Style 10110120103"
},
"partnerId": 2
}
}];
let wantedData = _.filter(configurationByCode, (config) => {
return _.includes(config.data.value.cols, 'parent_sku');
});
console.log( wantedData );
https://jsfiddle.net/76cndsp2/

Replacing items in JSON using Javascript

I am new to javascript. I am trying to replace a JSON elements with a set values passed from another function. When i parse the object I am getting an error message unexpected token at pos 0.
Thank you.
var defaultMessage = {
"MTI": "1101",
dataElements: {
"DE01": "101",
"DE02": "201",
"DE03": "301",
"DE04": "401",
"DE05": "501",
"DE06": "601",
"DE07": "701"
}
}
replaceDefaultElements: (testElements) => {
console.info(testElements)
console.info(defaultMessage);
var messageElements = JSON.parse(defaultMessage.dataElements);
Object.keys(testElements).forEach(function (key) {
messageElements[key] = testElements[key];
});
return messageElements;
}
//Calling from JEST test function:
test('Should be ', () => {
expect(functions.replaceDefaultElements('{"MTI":"1101",{"DE01":"XXX"}}')).toEqual({
"MTI": "1101",
dataElements: {
"DE01": "XXX",
"DE02": "201",
"DE03": "301",
"DE04": "401",
"DE05": "501",
"DE06": "601",
"DE07": "701"
}
})
When i parse the object I am getting an error message unexpected token at pos 0.
defaultMessage.dataElements is a JavaScript object. It isn't JSON.
Don't use JSON.parse there.
testElements, on the other hand, is JSON.
Replace JSON.parse(defaultMessage.dataElements) with defaultMessage.dataElements
Replace Object.keys(testElements) with Object.keys(JSON.parse(testElements))
Hope it will work

Extract data from API Object in React

I'm trying to retrieve data from an API with the following JSON output and I have a function in react that I call.
I can see the api output in console.log(users) so the data is being passed into the function.
I am trying to output the array contained in "data" but can't seem to access the data.
{
"dataCount": 2,
"data": [
{
"name": "Test review header",
"text": "This is adescription for a test review",
"img": "http://pngimg.com/upload/pigeon_PNG3423.png"
},
{
"name": "Test review header2",
"text": "This is adescription for a test review2",
"img": "http://pngimg.com/upload/pigeon_PNG3422.png"
}
]
}
renderUsers() {
const { users } = this.props;
console.log(users);
Object.keys(users).map(name => users[name])
console.log(users[name]);
};
The data you need to iterate over is present in the data field of users.
When you are using lists you have to specify the key property, to make react keep track of each item in list.
renderUsers() {
const { users } = this.props;
return (
<ul>
{
users.data.map(name => {
<li key={name}>users[name]</li>
})
}
</ul>
)
}
First of all, I don't use react but what you want should be the same in other javascript frameworks.
Are you sure that it is JSON you receive?
We need to be sure that you receive a JSON object and not normal text. Lets say you have a function parseResponse(data). We can call JSON.parse(data) to parse the data param to a json object. It is also possible that you store the result in a variable.
Using the JSON object
When we are sure you have the param parsed to a JSON object, we get it's data. For example, if you want to get the name of the first object in data, you can call:
parsedJson.data[0].name
where parsedJson is the result of JSON.parse(data),
data is an array of objects in the JSON,
0 is the first object in the array
It is possible that you have this kind of function then:
function parseResponse(data) {
var parsedJson = JSON.parse(data);
for(var i = 0; i < parsedJson.data.length; i++) {
console.log(parsedJson.data[i].name);
}
}
see jsfiddle

Categories

Resources