I'm having hard time in success to iterate over my external json file in Vue.
I'm importing the file like this:
import json from '../../public/platform.json'
export default {
data: () => ({
currentPage: 0,
brand: '',
platform: '',
affiliate: '',
myJson: json,
}),
Json file looking like this:
{
"Example": {
"Username": "",
"Password": "",
"AffiliateID": "",
"GI": "",
"CI": "",
"freeTextArea": ""
},
"ExampleTwo": {
"Username": "",
"Password": "",
"freeTextArea": ""
}
}
My goal is to do as follows:
I want to check if the "platform" from data is matching "Example" or "ExampleTwo" and if it does, I want to access the fields within either of them.
How can I do it?
You can use a computed property as follows:
computed: {
myPlatform: function () { return json[this.platform] || {}; },
}
Here is a demo: https://codesandbox.io/s/clever-gould-3hkbl?fontsize=14&hidenavigation=1&theme=dark
Related
I want to filter specific object using nested object element this
"token": "4f1f17f6503e4c5a3a269ecf93d6c92d"
This my data:
const data = [
{
name: "test",
token: {
expiryTime: "2021-09-24T12:27:30.654Z",
purpose: "ForgotPassword3",
token: "4f1f17f6503e4c5a3a269ecf93d6c92d",
},
user_id: "acaacc940c9ebfe798dee68acf5c",
zipcode: "",
},
{
name: "df ",
token: null,
user_id: "e0efe9810ca289ccd590bce48051",
zipcode: "",
},
{
name: "Io",
phone: "88888888",
state: "NY",
token: null,
user_id: "c88ce38d0c86f786c3a4b0f9f967",
zipcode: "13201",
},
];
Expected output is:
Data array inside the first object of token using filter object. Below given expected out.
const data = [
{
name: "test",
token: {
expiryTime: "2021-09-24T12:27:30.654Z",
purpose: "ForgotPassword3",
token: "4f1f17f6503e4c5a3a269ecf93d6c92d",
},
user_id: "acaacc940c9ebfe798dee68acf5c",
zipcode: "",
},
];
If you want a specific object, you could use find instead of filter. find will return the first element which verifies the condition specified to the find method where as the filter method is used to filters all the elements and returns all the element that matches the condition withing an array.
*You need to add the optional chaining ?. because the token object might be null like you have in some of your data
here both examples:
const data = [
{
"name": "test",
"token": {
"expiryTime": "2021-09-24T12:27:30.654Z",
"purpose": "ForgotPassword3",
"token": "4f1f17f6503e4c5a3a269ecf93d6c92d"
},
"user_id": "acaacc940c9ebfe798dee68acf5c",
"zipcode": ""
},
{
"name": "df ",
"token": null,
"user_id": "e0efe9810ca289ccd590bce48051",
"zipcode": ""
},
{
"name": "Io",
"phone": "88888888",
"state": "NY",
"token": null,
"user_id": "c88ce38d0c86f786c3a4b0f9f967",
"zipcode": "13201"
}
]
const resFilter = data.filter(x => x.token?.token === "4f1f17f6503e4c5a3a269ecf93d6c92d");
console.log(resFilter);
const resObj = data.find(x => x.token?.token === "4f1f17f6503e4c5a3a269ecf93d6c92d");
console.log(resObj);
You must use the following code
const finded = data.filter(user => user?.token?.token ==="value"})
console.log(finded);
so I'm working on an app in which I receive an array from getDerivedStateFromProps, and with that set the state of list, this is an example of the array:
const data = [
[
{
"exerciseName": {
"exerciseName": "Barbell Bench Press",
},
"key": 0.4867576438357962,
"numOfSets": 1,
"paddingBottom": 30,
"reps": "",
"reps2": "",
"reps3": "",
"reps4": "",
"sets": "",
"sets2": "",
"sets3": "",
"sets4": "",
"weigth": "",
"weigth2": "",
"weigth3": "",
"weigth4": "",
},
],
]
as you can see is a nested array and that's probably why it doesn't let me display it in the Flatlist. This is the function I use to get the list:
class mondayExercises extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
}; }
static getDerivedStateFromProps(props, state) {
if (props?.list) {
const mergedArray = [].concat.apply([], props.list);
const flatten = mergedArray.flat(1);
return {
list: [...state.list, flatten],
};
}
return null;
}
I already managed to merge the arrays together, but is there a way to flatten it without changing the entire code of the app?
I'm having hard time on thinking how will I populate hooks with API response(json)
see below codes
cosnt [loginResponse, setloginResponse] = useState({
Token: '',
UserID: '', //from user-id
UserName: '', //from user-userName
firstName: '', //from user-firstName
rcCode: '' //from attributes-rcCode
})
const login = async () => {
await axios.get('/API')
.then(response => {
console.log('response.data', response.data.resp)
});
}
here's the result of console.log(response.data.resp)
{
"data": {
"token": "abcd",
"user": {
"id": "123456",
"userName": "uname",
"firstName": "FNAME",
"lastName": "MNAME",
"email": "email#email.com",
"attributes": {
"favorites": ["FAV"],
"rcCode": ["123"]
},
"requiredActions": [],
"roles": ["ROLE"]
},
"modulePermissions": []
}
}
for console.log(response.data):
"resp": {
"data": {
"token": "abcd",
"user": {
"id": "123456",
"userName": "uname",
"firstName": "FNAME",
"lastName": "MNAME",
"email": "email#email.com",
"attributes": {
"favorites": ["FAV"],
"rcCode": ["123"]
},
"requiredActions": [],
"roles": ["ROLE"]
},
"modulePermissions": []
}
},
"success": true
I want to populate my hooks with those datas for me to utilize it on my page.
I got undefined if I tried to console.log(response.data.resp.data)
On console.log(response), I got:
Thank you.
Don't use async/await and .then() together. Use either of those.
const login = async () => {
const response = await axios.get('/API');
const parsedData = JSON.parse(response.data.resp);
const userData = parsedData.data;
setLoginResponse({
Token: userData.token,
UserID: userData.user.id,
UserName: userData.user.userName,
firstName: userData.user.firstName,
rcCode: userData.user.attributes.rcCode
});
}
In the .then
setLoginResponse({...loginResponse, Token: response.data.resp.data.token, UserId: response.data.resp.data.user.id, ...}
You can destructure your response object first and store values in variables to make the setLoginResponse more easy to read.
https://reactjs.org/docs/hooks-state.html
This question already has answers here:
How to iterate over a JavaScript object?
(19 answers)
Closed 1 year ago.
I'm having trouble to iterate over JSON file and get his parameters, this is an example of JSON file i created:
{
"One": { "Username": "", "Password": "", "unique3": "", "unique4": "", "unique5": "", "freeTextArea": "" },
"Two": { "Username": "", "Password": "", "SecretKey":"", "Autologinurl":"", "CrmUid":"", "freeTextArea":"" },
"Three": { "Username": "", "Password": "", "freeTextArea": "" }
}
I have this HTML input attribute:
<input type="text" name="platform" placeholder="Platform" id="platform"/>
What I want is to check if the Input is matching "one"/"two"/"three" from the JSON, and then create new input elements using DOM based on the parameters "one"/"two"/"three" have.
This is how I'm getting the JSON data using AJAX:
var platformJson = $.getJSON("platform.json");
How can I iterate correctly over this JSON file?
Get value of #platform input using .val()
Search for this value in data object and get the target
If the latter exists, iterate over it using $.each and append a new input to #platformForm using .append
const data = {
"One": { "Username": "1", "Password": "1", "AffiliateID": "1", "GI": "1", "CI": "1", "freeTextArea": "1" },
"Two": { "Username": "2", "Password": "2", "SecretKey":"2", "Autologinurl":"2", "CrmUid":"2", "freeTextArea":"2" },
"Three": { "Username": "3", "Password": "3", "freeTextArea": "3" }
};
const platform = $('#platform').val();
const props = data[platform];
if (props) {
$.each(props, function(prop, value) {
$('#platformForm').append(
`<input id="${prop}" value="${value}" />`
);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="platformForm">
<input type="text" name="platform" placeholder="Platform" id="platform" value="One"/>
</form>
You could try
$.getJSON('https://jsonplaceholder.typicode.com/todos/1', function (data) {
$.each(data, function (key, val) {
console.log(key);
});
});
Basically you need to provide a callback to the getJSON() method, which will be run with the JSON that you got back.
Then you should iterate via $.each() which will restructure and give you the key and value of the JSON.
Then you could manipulate and do what you need to do.
You don't need to "iterate" access the value from a JavaScript object by key. You can do the following:
const response = {
"One": {
"Username": "one",
"Password": "",
"AffiliateID": "",
"GI": "",
"CI": "",
"freeTextArea": ""
},
"Two": {
"Username": "",
"Password": "",
"SecretKey": "",
"Autologinurl": "",
"CrmUid": "",
"freeTextArea": "",
},
"Three": {
"Username": "",
"Password": "",
"freeTextArea": ""
}
}
const inputValue = $('#platform').val();
const keys = Object.keys(response);
console.log(keys.includes(inputValue));
const obj = response[inputValue];
console.log(obj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="platform" placeholder="Platform" id="platform" value="One" />
I recommend using lowerCase keys for your JSON, so that it'll be easier for you to match throughout the application.
Hello my problem is i wont create, update or delete {note} in array [notes] finded by operationId in parent array id. but i dont now ho to do it. i have ADDNOTE but it not working.
i write i put here only ADDNOTE, becouse with these i cant event start DELETE and UPDATE
my default
const initialState = {
loading : false,
isLoaded: false,
person : {
id:'',
firstName: '',
operations:[],
},
error : ''
};
my code :
case ADDNOTE: return {
...state,
person:
{
...state.person,
operations:[
]
state.person.operations.find(item => item.id === action.payload.operationId).notes.push(action.payload)
}
};
action.payoload
{
"id": "22",
"operationId" : "123A",
"note": "bla bla"
}
what i wont :
{
"loading" : false,
"person" : {
"id": "" ,
"firstName": "",
"operations":[
{
"id" : "123A",
"notes": [
{
"id": "11",
"operationId" : "123A",
"note": "bla"
},
{
"id": "22",
"operationId" : "123A",
"note": "bla bla"
}
]
},
{
"id" : "456B",
"notes": [
{
"id": "99",
"operationId" : "456B",
"note": "bla xxx"
}
]
}
]
},
"error" : ""
}
I think the following would work:
case ADDNOTE: return {
...state,
person: {
...state.person,
operations: state.person.operations.map((operation) =>
operation.id !== action.payload.operationId
? operation //not this operation, just return original
: { // add note
...operation,
notes: [...operation.notes, action.payload],
}
),
},
};
More information on how to update can be found here