array of objects as parameters on request POST axios - arrays

I am working on a project with vue.js and to handle my AJAX requests I use Axios, I wonder if it is possible to pass as a parameter to a POST request an array of objects, of this type:
[{id: 1, name: 'max'}, {id: 2, name: 'jhon'}, {id: 3, name: 'anna'}]
If possible, what is the best way to do this?

Sure!
let arrOfObj = [
{ name: 'John', lastName: 'Doe' },
{ name: 'Jane', lastName: 'Doe' }
]
axios.post('url_here',arrOfObj)
.then(console.log)
.catch(console.log)

Yes, it's very possible
let data = [
{id: 1, name: 'max'},
{id: 2, name: 'jhon'},
{id: 3, name: 'anna'}
];
let formdata = new FormData();
formdata.append('data',JSON.stringify(data));
axios.post('/url`',formdata)
.then(res => console.log(res))
.catch(err => console.log(err)
On the receiving end (assuming it's PHP & Laravel)
$data = json_decode($request->data);
then loop through $data as it's a normal array

Lema's answer was the only one that worked for me while using axios + vue + .net Core.
I was trying to send a post to my backend which was expecting an array. Following Lema's implementation I received an string and then deserialized the json string to the type I was expecting.
public IActionResult PostMethod([FromForm]string serialized_object_name){
var expectedArray = JsonConvert.DeserializeObject<ArrayTypeNeeded[]>(serialized_object_name);
}

Related

sending multiple objects using axios

How can I send multiple objects in axios ? is there a way to send an array to an API using axios ?
This is the code.
export const addOrderAdmin = (ownerID,array) => api.patch(`/checkout/${ownerID}`,
{
delivery: array // array with 2 objects.
}
)
and the objects was like this.
is it possible ?
you could always create an array of nested objects
example:
var customerInfo = {
name: 'bob',
phone : 'xxx-xxx-xxxx',
address: [
{
id: 1,
city: 'Buffalo'
},
{
id 2,
city: 'Houston'
]
}
then you could just patch the customerInfo object and you can use interpolation with dot accessor notation for the url

How to get values in [object Object] in to an Array or how can i access those values in Angular

This is my Angular Code which i have written in component.ts file.I am getting data from backend API and try to console.log and see the data.
getInfo() {
const params = [];
params.push({code: 'Code', name: 'ty_PSD'});
params.push({code: 'continentCodes', name: ['CAN']});
params.push({code: 'dateFrom', name: '2019-01-01'});
params.push({code: 'dateTo', name: '2019-12-31'});
params.push({code: 'statusType', name: 'REAL'});
params.push({code: 'valueType', name: 'TTV'});
this.serviceHandler.getDemand([], params).subscribe(
demand => {
console.log(demand + 'ddd');
});
}
But in here console.log(demand + 'ddd'); api response is shown like this.
This is my console.log(demand) output.
How could i get values in data: Array(365) values in to an array.
You should not concatenate/sum an object with a string because console.log parses the object as a string.
I think you want the number 4 in the examples bellow: console.log(JSON.stringify(obj) + 'aaa');
var obj = { a: 'aa', b: 0, c: true};
console.log(1, obj + 'aaa');
console.log(2, obj);
console.log(3, JSON.stringify(obj));
console.log(4, JSON.stringify(obj) + 'aaa');
The API response is in string format. You need to parse it.
Try:
console.log(JSON.parse(demand))

console logging event target id of an object in an array in an object in react

i am mapping multiple area on an image for a web app in react, i want to target their id's onClick
let targetArea = myMap.find(targetArea => targetArea.id === 10)
let MAP = {
id: 'map', name: 'my-map',
areas: [
{id: 7, name: 'kitchen', shape: 'rect', coords: [804,1001,1019,1135], preFillColor: 'clear'},
{id: 9, name: 'bar pendant', shape: 'rect', coords: [516,1294,732,1428], preFillColor: 'clear'},
{id: 10, name: 'entry', href: 'entry', shape: 'rect', coords: [1034,1292,1246,1428], preFillColor: 'clear'}
]
};
i was getting an array of objects back with console.log(MAP.areas)
but i'm not sure how to dynamically set an id
so far i've got
const myMap = MAP.areas
let targetArea = myMap.find(targetArea => targetArea.id === 10)
areaCheck = (event) => {
console.log(targetArea.name)
}
i'm getting the correct name of the hard set id in my targetArea variable, i feel like i might need a loop idk??
first i passed area as an argument in the onClick event handler
onClick={(area)=> this.areaCheck(area)}
then passed it around my handler
areaCheck = (area) => {
console.log(area.id)
this.setState({ areaClicked: area.id })
}
then it suddenly knew what area i was talking about :)

Multidimensional Arrays, Vuex & Mutations

I'm attempting to both add and remove items in a multidimensional array stored in Vuex.
The array is a group of categories, and each category and have a sub-category (infinity, not simply a two dimensional array).
Example data set is something like this:
[
{
id: 123,
name: 'technology',
parent_id: null,
children: [
id: 456,
name: 'languages',
parent_id: 123,
children: [
{
id:789,
name: 'javascript',
parent_id: 456
}, {
id:987,
name: 'php',
parent_id: 456
}
]
}, {
id: 333,
name: 'frameworks',
parent_id 123,
children: [
{
id:777,
name: 'quasar',
parent_id: 333
}
]
}
]
}
]
....my question is, how do I best add and remove elements to this array, which is inside of a Vuex Store?
I normally manipulate simple arrays inside the Vuex Store using Vue.Set() to get reactivity. However, because I'm not sure how deep the nested array being manipulated is - I simply can't figure it out.
Here's an example of how I thought I could add a sub-category element using recursion:
export const append = (state, item) => {
if (item.parent_uid !== null) {
var categories = []
state.data.filter(function f (o) {
if (o.uid === item.parent_uid) {
console.log('found it')
o.push(item)
return o
}
if (o.children) {
return (o.children = o.children.filter(f)).length
}
})
} else {
state.data.push(item)
}
}
The first thing to understand is that vuex, or any other state management library based on flux architecture, isn't designed to handle nested object graph, let alone arbitrary/infinity nested objects that you mentioned. To make the matter worse, even with shallow state object, vuex works best when you define the shape of the state (all desired fields) upfront.
IMHO, there are two possible approaches you can take
1. Normalize your data
This is an approach recommended by vue.js team member [here][2].
If you really want to retain information about the hierarchical structure after normalization, you can use flat in conjunction with a transformation function to flatten your nested object by name to something like this:
const store = new Vuex.Store({
...
state: {
data: {
'technology': { id: 123, name: 'technology', parent_id: null },
'technology.languages': { id: 456, name: 'languages', parent_id: 123 },
'technology.languages.javascript': { id: 789, name: 'javascript', parent_id: 456 },
'technology.languages.php': { id: 987, name: 'php', parent_id: 456 },
'technology.frameworks': { id: 333, name: 'frameworks', parent_id: 123 },
'technology.frameworks.quasar': { id: 777, name: 'quasar', parent_id: 333 },
}
},
});
Then you can use Vue.set() on each item in state.data as usual.
2. Make a totally new state object on modification
This is the second approach mentioned in vuex's documentation:
When adding new properties to an Object, you should either:
Use Vue.set(obj, 'newProp', 123), or
Replace that Object with a fresh one
...
You can easily achieve this with another library: object-path-immutable. For example, suppose you want to add new category under languages, you can create a mutation like this:
const store = new Vuex.Store({
mutations: {
addCategory(state, { name, id, parent_id }) {
state.data = immutable.push(state.data, '0.children.0.children', { id, name, parent_id });
},
},
...
});
By reassigning state.data to a new object each time a modification is made, vuex reactivity system will be properly informed of changes you made to state.data. This approach is desirable if you don't want to normalize/denormalize your data.

How do you select a particular field from a response string which we receive in form of JSON

I have a sample response which I received, the structure is something like this:
A = [{ user:
{ score_level: 16,
is_system: false,
location: 'Mumbai',
email: 'abc#xyz.org',
image: 'example.org',
firstname: Steve},
details: { solution_count: 1, average_rating: 1, recommendation_count: 0 },
score: 45},
{ user:
{ score_level: 17,
is_system: false,
location: 'Miami',
email: 'ab.org',
image: 'example.net',
firstname: Mark},
details: { solution_count: 1, average_rating: 1, recommendation_count: 0 },
score: 50}]
We are getting some information about the user, so what I would like to do is to get only the fistname for every user from this file.
I tried using:
var read = JSON.parse(A);
var firstname = read["user"]["firstname"];
But this dosent seem to work, can you suggest a solution for this?
You can map through the array of objects, check if the object is a user object, and if so, return the firstname. This will yield an array of firstname values.
const names = A.map((obj) => {
if (obj.user) {
return obj.user.firstname;
}
});

Resources