I'm new in Vue js, and I have data in array object like below when I use vue-multiselect.
[
{
"id": 1,
"add_on_type": "Xtra",
"name": "test",
"price": 12,
"created_at": "2020-06-25 10:12:43",
"updated_at": "2020-06-25 10:12:43"
},
{
"id": 3,
"add_on_type": "Xtra",
"name": "Some x",
"price": 120,
"created_at": "2020-06-30 05:47:52",
"updated_at": "2020-06-30 05:47:52"
}
]
but in my function I need to access like key:value like below
"xtra": {
// key: value
0: 1
1: 3
}
but I get all array object instead of id only. I need to get the ID only in array, below is my code. I don't know how to get only id from array using below code.
this.$axios
.get("items/" + this.item)
.then(res => {
// below line is how I get the array object, but I need only id in array.
data.xtra = this.extra;
console.log(data);
})
.catch(err => {
throw err;
});
this maybe easy for some people, but I cannot find the way to to do. any help would be appreciated. thanks in advance
If I understood correctly your question, this.item is holding an object retrieved from the array. If is like this, it should be as easy as:
.get("items/" + this.item.id)
if you want to create new array you can do this at your return from axios
.then(res => {
let arr = res.data
this.xtra = arr.map(x =>
x.item.id)
})
First declare Items as reactive array in setup function
const tools = reactive([]);
Then in methods, retrieve
axios.get("/user-items").then(response => {
var items = [];
response.data.forEach((item, index) => {
items.push(item.id);
})
Object.assign(this.items, items);
});
Related
I made a request to an endpoint and I get this object, I'm filtering the name like this:
fetch('http://endpoint', requestOptions)
.then((response) => response.json())
.then((result) => {
const onlineUsers = result.resource.items[1].onlineUsers >= 1;
console.log(onlineUsers);
})
.catch((error) => console.log('error', error));
This workers, but I just need the result of what is in the key named Forms, but there is a possibility that it will change its position, so the items[1] it may not work anymore
This is an example of the object I receive:
{
"type": "application/vn+json",
"resource": {
"total": 4,
"itemType": "application",
"items": [
{
"name": "Test",
"onlineUsers": 1
},
{
"name": "Forms",
"onlineUsers": 1
},
{
"name": "Users",
"onlineUsers": 7
},
{
"name": "OnlineUsers",
"onlineUsers": 5
}
]
},
"method": "get",
"status": "success"
}
Is there any way to receive this object and filter by name? Like:
if (hasName === "Forms", get onlineUsers) {
// Do something
}
Thanks!
As suggested in your question, you can use filter on your array. Something like that:
console.log(
result.resource.items.filter((item) => item.name === "Forms")
);
This will print an array with all items having the name Forms. Using your example:
[
{
"name": "Forms",
"onlineUsers": 1
}
]
If there is only one item with the name Forms, or if you want only the first one, find may be a good alternative with a similar syntax:
console.log(
result.resource.items.find((item) => item.name === "Forms")
);
This will only print the first found object (or null if none is matching), without the array "pollution":
{
"name": "Forms",
"onlineUsers": 1
}
result.resource.items.filter((item) => item.name === "Forms")
Will filter your objects for you
Note, you will get back an array of all the filtered objects meeting the condition.
If you know there's only one object that matches that name you can use find which will return the first match so you don't necessarily need to iterate over the entire array.
Here's a little general function that might help. Pass in the data, the value of name, and the property you want the value of. If there is no match it returns 'No data'.
const data={type:"application/vn+json",resource:{total:4,itemType:"application",items:[{name:"Test",onlineUsers:1},{name:"Forms",onlineUsers:1},{name:"Users",onlineUsers:7},{name:"OnlineUsers",onlineUsers:5}]},method:"get",status:"success"};
function finder(data, name, prop) {
return data.resource.items.find(item => {
return item.name === name;
})?.[prop] || 'No data';
}
console.log(finder(data, 'Forms', 'onlineUsers'));
console.log(finder(data, 'morf', 'onlineUsers'));
console.log(finder(data, 'Users', 'onlineUsers'));
console.log(finder(data, 'Users', 'onlineUser'));
I am having a array of objects which looks like this
var data = [
{
"id": "K014-s1",
"status": true,
"amount": 992,
"check": true,
},
{
"id": "K014-s2",
"status": false,
"amount": 10992,
"check": true,
}
]
I want only certain key values from the object in the array
Required Output:
var data = [
{
"id": "K014-s1",
"amount": 992,
},
{
"id": "K014-s2",
"amount": 10992,
}
]
Code I tried:
var filteredData = []
var result = data.map((obj) => {
filteredData.push(obj.id)
})
console.log(filteredData)
I tried. But don't Know how to make it. Please Help me with some solutions
instead of pushing object to another array,you can simply map your data like this
var result = data.map((obj) => {
return {
id:obj.id,
amount:obj.amount
}
})
Array.prototype.map already creates a new array, so result will already be the new value you are looking for.
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
var filteredResult = data.map((obj) => {
//additional logic, if needed here.
return {
id: obj.id,
amount: ob.amount,
}
})
Alternatively you can of course use a for loop or array.prototype.forEach to achieve the same:
var filteredData = []
data.forEach((obj) => {
filteredData.push({
id: obj.id,
amount: ob.amount,
})
})
No need to initiate a new array because the map method returns a new array what you can do is map the array then delete the property or method that you want then return the new array. Here's a simple solution that you use for your reference
const filteredData = data.map(newData => {
delete newData.status
delete newData.check
return newData
})
Simply you can loop over array using forEach method and delete key, value pairs. For example data.forEach((obj) => { delete obj.status; delete obj.check; }) since array is a reference type you can easily mutate it and not create a duplicate of data.
I am trying to iterate this data on vue inside the method function
{
"data": [
{
"id": 1,
"name": "Jack Daniels",
"mobile": "21223",
"start": "2021-02-25T09:16:21.000000Z",
"end": "2021-02-25T09:16:21.000000Z"
}
]
}
here is my code
async getEvents() {
try {
const response = await axios.get('/api/customers')
Object.entries(response).forEach(([key, value]) => {
console.log(`${key}:${value}`)
})
} catch (err) {
console.log(err)
}
}
and here is the output on
data:[object Object],[object Object]
any idea what went wrong and if there is better approach for iterating the data in vue.js
First of all it's not Vue question(axios/js tags).
You don't need Object.entries here (if you need to iterate data array).
Just use map for array and that's all.
const iteratedData = response.data.map((item, index) => {
console.log(`Index ${index}`);
console.log(item);
// Do what you need with data, your iteration
return item;
});
Code is fine. Here key is data and value is array of object. so to access value, here is a sample code
let response = {
"data":[{
"id":1,
"name":"Jack Daniels",
"mobile":"21223",
"start":"2021-02-25T09:16:21.000000Z",
"end":"2021-02-25T09:16:21.000000Z"
}]
};
Object.entries(response).forEach(([key,value])=>{
console.log(`${key}:${value[0].id}`)
})
Here value is an array so iterate value to get properties. It is just a sample to show logic.
So I've got this part of a code where I'm creating response for my project. Now I've managed to create data, but I've got response that I need to changes.
First here is my code:
exports.getById = (req, res) => {
const id = req.params.a_id;
articleService
.getById(id)
.then((article) => {
bankService
.getRates()
.then((list) => {
let prr = article.price;
let price = parseFloat(prr.replace(/\.| ?€$/g, '').replace(',', '.'));
let mjeseci = req.body.months;
let ratanks = list.map((rata) =>
LoanJS.Loan(price, !mjeseci ? 60 : mjeseci, rata.NKS)
);
const kreditNKS = ratanks.map((index) => index.sum);
const rataNKS = ratanks.map(
(index) => index.installments[0].installment
);
let eks = list.map((stopa) => stopa.EKS);
let name = list.map((ime) => ime.bank.name);
let nks = list.map((stopa) => stopa.NKS);
let type = list.map((ime) => ime.interest_type.name);
res.status(200).json({
kredit: {
kreditNKS: kreditNKS,
rataNKS: rataNKS,
stopaEKS: eks,
stopaNKS: nks,
tip: type,
ime: name,
}
})
.catch((err) => {
res.status(500).send('Error 1 ->' + err);
});
})
.catch((err) => {
res.status(500).send('Error ->' + err);
});
};
Explain of what it does: So I'm fetching single article from my DB which has price inside it, then I'm getting data about loan also from DB. Now I'm using that data from DB, using .map function to get values one by one and calculating for that values my final loan(that is ratanks part). Now I'm also extracting some other data that I need present to the user on the frontend.
Now my problem: It's sending my res as an object with one object, who has key:value pairs and values are array of data inside it. But I want it to be an array with multiple objects.
My response in postman right now:
{
"kredit": {
"kreditNKS": [
118406.54,
118348.2,
119400.33,
118022.46,
118262.44,
118811.84
],
"rataNKS": [
19734.42,
19724.7,
19900.05,
19670.41,
19710.41,
19801.97
],
"stopaEKS": [
"6.24",
"5.65",
"8.26",
"3.13",
"4.03",
"5.68"
],
"stopaNKS": [
"4.11",
"3.94",
"7",
"2.99",
"3.69",
"5.29"
],
"tip": [
"Fiksna",
"Promjenjiva",
"Fiksna",
"Promjenjiva",
"Fiksna",
"Fiksna"
],
"ime": [
"ZiraatBank",
"ZiraatBank",
"UniCredit",
"Raiffeisen Bank",
"Raiffeisen Bank",
"ASA Banka"
]
}
}
Where I need it to be something like this:
[
{
"kreditNKS":118406.54,
"rataNKS": 19734.42,
"stopaEKS": "6.24",
"stopaNKS": "4.11",
"tip": "Fiksna",
"ime": "ZiraatBank"
},
{
"kreditNKS":118348.2,
"rataNKS": 19724.7,
"stopaEKS": "5.65",
"stopaNKS": "3.94",
"tip": "Promjenjiva",
"ime": "ZiraatBank"
},
{
"kreditNKS":119400.33,
"rataNKS": 19900,05,
"stopaEKS": "8.26",
"stopaNKS": "7",
"tip": "Fiksna",
"ime": "UniCredit"
}
etc.....
]
Is it possible to modify something like this?
Any tips are welcome!
Thanks!
it looks like you're mapping your list into 4 arrays and then putting them inside a single object, where each array is a property of the said object.
let eks = list.map((stopa) => stopa.EKS);
let name = list.map((ime) => ime.bank.name);
let nks = list.map((stopa) => stopa.NKS);
let type = list.map((ime) => ime.interest_type.name);
res.status(200).json({
kredit: {
kreditNKS: kreditNKS,
rataNKS: rataNKS,
stopaEKS: eks,
stopaNKS: nks,
tip: type,
ime: name,
}
})
The way someArray.map(eachThing => doSomethingWithThing(thing)) works is that you iterate the entire array "someArray" and execute a function for each thing inside of it.
This means that instead of doing LoanJS.Loan(price, !mjeseci ? 60 : mjeseci, rata.NKS) for all the items of the list and write that to a new array called "ratanks", you can write your own function for all the items of the list, and during the iteration of each item do something like const loan = LoanJS.Loan(price, !mjeseci ? 60 : mjeseci, eachItem.NKS).
This being said, you should be able to get the object you want by mapping your list into an array of objects like this
const mappedKredits = list.map((eachObject) => {
const computedLoan = LoanJS.Loan(price, !mjeseci ? 60 : mjeseci, eachObject.NKS);
const kreditNKS = computedLoan.sum;
const rataNKS = computedLoan.installments[0].installment;
return {
"kreditNKS": kreditNKS,
"rataNKS": rataNKS,
"stopaEKS": eachObject.EKS,
"stopaNKS": eachObject.NKS,
"tip": eachObject.interest_type.name,
"ime": eachObject.bank.name,
}
});
res.status(200).json(mappedKredits);
Btw, try to use more descriptive names for the variables, if they're in English it'll be even better, otherwise, it makes it a bit harder for folks like me to understand what the code is doing, thus making it harder to help you.
1. I am building a JSON file
const _ = require('lodash');
let dataGroupedByMndtId = _.groupBy(
_.orderBy(data.Entries, 'mndtId'), 'mndtId'
);
let transactionsPerEntry = [];
_
.map(dataGroupedByMndtId, (transactions, index) => {
// verticalBarChartData.push(`{ "name": "${index}"}`);
_.map(
transactions, (transaction, index) => {
transactionsPerEntry.push(`{ "name": "${transaction.date}", "value": "${transaction.amount}"}`);
}
);
verticalBarChartData.push(`{ "name": "${index}", "series": [${transactionsPerEntry}]}`);
transactionsPerEntry = [];
});
outputJsonFile = 'generated.json';
outputJsonPath = path.join(__dirname, 'data', outputJsonFile);
try {
fs.writeFileSync(outputJsonPath, verticalBarChartData, { mode: 0o755 });
} catch (err) {
// An error occurred
console.error(err);
}
2. The generated JSON misses enclosing square brackets
{
"name": "1/0003/1",
"series": [{
"name": "2019-04-05T00:00:00Z",
"value": 20.87
}, {
"name": "2019-03-03T00:00:00Z",
"value": 5.74
}]
}, {
"name": "1/0004/1",
"series": [{
"name": "2019-04-03T00:00:00Z",
"value": 15.7
}, {
"name": "2019-03-26T00:00:00Z",
"value": 0.13
}]
}
QUESTION
How could I add enclosing square brackets?
I tried several ways :
adding enclosing brackets (stringify) and parsing the string (JSON.parse) but the square brackets disappear
add [] around the verticalBarChart variable
push an empty item
thank you for your help
I would strongly recommend not handcrafting JSON. Instead, build the structure and then let JSON.stringify do the work.
You're also misusing _.map. If you aren't returning a value from its callback and you're not using _.map's return value, _.map is the wrong tool. You'd use _.each instead. (Or use ES5's forEach.) Or of course, return something from the callback and use the returned result, since you do seem to be doing a mapping operation.
Here's what I think you're trying to do:
const _ = require('lodash');
let dataGroupedByMndtId = _.groupBy(
_.orderBy(data.Entries, 'mndtId'), 'mndtId'
);
let verticalBarChartData = _.map(dataGroupedByMndtId, (transactions, index) => ({
name: String(index), // You seem to want it to be a string, not a number
series: _.map(transactions, (transaction, index) => ({
name: transaction.date, // May need String() around that
value: transaction.amount // And may need String() here too, if you really want a string
}))
}));
outputJsonFile = 'generated.json';
outputJsonPath = path.join(__dirname, 'data', outputJsonFile);
try {
fs.writeFileSync(outputJsonPath, JSON.stringify(verticalBarChartData), { mode: 0o755 });
} catch (err) {
// An error occurred
console.error(err);
}
I've used _.map there because you were, but you could just as easily use ES5's Array.prototype.map.
Another solution is the replacement of line [A] by [B] but this is less convenient than #t-j-crowder ' solution
[A] verticalBarChartData.push({ "name": "${index}", "series": [${transactionsPerEntry}]});
[B] verticalBarChartData.push(JSON.parse({ "name": "${index}", "series": [${transactionsPerEntry}]}));