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.
Related
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.
Been delivered some confusing JSON data with a problem I haven't seen before.
The JSON is formatted similar to this structure:
[
{
"title": "Event",
"start_date": "2022-08-20 15:00:00",
"end_date": "2022-08-20 16:00:00",
"branch": {
"85": "branchname"
},
"room": {
"156": "roomname"
},
"age_group": {
"5": "Youth",
"6": "Teen"
}
},
{
"title": "Event02",
"start_date": "2022-08-20 15:00:00",
"end_date": "2022-08-20 16:00:00",
"branch": {
"72": "branchname"
},
"room": {
"104": "roomname02"
},
"age_group": {
"5": "Youth",
"6": "Teen"
}
}
]
I'm trying to pull roomname out of the data, but it's nested in an object that has a random index number. If I manually put in the index number, I can retrieve the data, but the number changes every entry.
If I can figure out how to retrieve the number and store it in a variable, then use it again, or just somehow wildcard to just show any child of any key under the parent node "room" it would work perfect, but I don't know of a way to do this in javascript.
I'm limited to vanilla javascript, no external libraries or jquery.
here is the code that will output correctly if I manually enter the index numbers, but it only works for a single entry.
<script>
const url = 'example.json';
fetch(url)
.then((response) => {
return response.json();
})
.then((json) => {
json.map(function(event) {
console.log(`${event.start_date}`);
console.log(`${event.title}`);
console.log(`${event.room[156]}`);
return element;
});
}, 80);
</script>
EDIT: Forgot to point out, there is always only 1 entry in the "room" tag, but it's index is randomized, so if you just select the room tag it returns undefined or invalid. If I could wildcard the index so it just tries them all, or somehow retrieve the index number and store it in a variable, it would fix the issue.
I think this will work:
Here as you don't know the key so, instead of just guessing, you can use Object.values(JSONObjName) to get the list/array of values in that json.
Here I'm also using optional chaining (?.) to handle the case when the json has no key value pairs.
<script>
const url = 'example.json';
fetch(url)
.then((response) => {
return response.json();
})
.then((json) => {
json.map(function(event) {
const roomName = Object.values(event.room)?.[0];
console.log(`${event.start_date}`);
console.log(`${event.title}`);
console.log(`${roomName}`);
return {...event, room: roomName};
});
}, 80);
</script>
As long as you always want the first key you can fetch it like this
room = event.room[Object.keys(event.room)[0]]
if you want to get just roomname, you could do Object.values(room)[0]
or if you want the index and value you could go for Object.entries(room)[0]
arr?.map(({ room }) => {
for(let [key, value] of Object.entries(room)) {
console.log('Random Key : ',key)
console.log('Roomname : ', value)
console.log('Using random key : ',room[key])
}
})
By this way you can find the value of room against the random key.
Or you can try this if it is more relevant to you.
arr.map(({ room }) => {
for(let key of Object.keys(room)) {
console.log('Random Key : ',key)
console.log('Using random key : ',room[key])
}
})
Since you may want to do this for branch as well, here's an alternative solution which uses the object key as a computed property name (aka "dynamic key") to get the value.
And since, in this example it's done more than once, I've added that to a function that you can call in the destructuring assignment.
const data=[{title:"Event",start_date:"2022-08-20 15:00:00",end_date:"2022-08-20 16:00:00",branch:{85:"branchname"},room:{156:"roomname"},age_group:{5:"Youth",6:"Teen"}},{title:"Event02",start_date:"2022-08-20 15:00:00",end_date:"2022-08-20 16:00:00",branch:{72:"branchname02"},room:{104:"roomname02"},age_group:{5:"Youth",6:"Teen"}}];
// Get first key from an object
function getKey(obj) {
return Object.keys(obj)[0];
}
const out = data.map(obj => {
// Destructure the object and call `getKey` with the
// object to get its only key, and use that
// as a computed property to get its value, which
// we then relabel e.g. `roomName`
const {
branch: { [getKey(obj.branch)]: branchName },
room: { [getKey(obj.room)]: roomName },
...rest
} = obj;
// Now just return a new object with your new keys/values
return { ...rest, branchName, roomName };
});
console.log(out);
Additional documentation
Rest parameters
Spread syntax
This is the Output: The data structure for the output is Map<String, List<Pair<String, String>>>
"testdata": [
{
"1.0": "True"
},
{
"1.1": "False"
}
]
Now I need to display this data on the UI as "testdata":["1.0","1.1","1.2"],
wherein here from the Pair, I want to fetch only the first elements from the Pair and put them in the structure Map<String, List<String>>
So how do I write that code in javascript in order to get that output?
this.previousData = versions.filter(v => v !== this.version).map(item => ({ text: item, value: item }))
How do I modify this code to get this output "testdata":["1.0","1.1","1.2"]?
You could try something like this:
// This assumes that there will be only one key in each array item, or the first key in each array item denotes the version
this.previousData =
versions
.filter(v => v !== this.version)
.map(item => Object.keys(item)[0])
// or as MikeT suggested, if you are only expecting something like this:
// [
// { "v1": "some value 1" },
// { "v2": "some value 2" },
// ... in general --> { "version": "some value" }
// ]
// you may try this as well
this.previousData =
versions
.filter(v => v !== this.version)
.map(item => Object.keys(item))
.flat()
your question isn't too clear about which element you are struggling with
so to get the data
async getData()
{
const resp = await fetch("<<your url from your java service>>" )
return await resp.json();
}
to format the data as you wish it to be formatted
formatData(json){
return json.testdata.map((i)=>Object.entries(i).map(([k,v])=>k)).flat()
}
and to display in vue
<template>testdata:{{testdata}}</template>
<script>
...
methods:{
async populatedata(){
const tmp = await getData()
this.testdata = formatData(tmp)
}
}
...
</script>
Object.entries will convert an object into a tuple array so {"1.0":"True","1.1":"False"} will become [["1.0","True"],["1.1":"False"]] which then lets you use tuple decomposition to get the keys
you could also use Object.keys() if you have no need for the values but that wasn't clear from the context so i gave you the more flexible option
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);
});
I was trying to return a JSON Object but instead it returns an array. I am using primary key for query so I am sure I will only get one result.
This is my approach :
router.get("/student_info/:id", (req, res, next) => {
connection.getConnection((error, currentConnection) => {
if (!!error) {
console.log("Error occurred while connecting db")
} else {
let id = req.params.id;
currentConnection.query("SELECT * FROM students WHERE id=" + "'" + id + "'", (error, rows, fields) => {
if (!!error) {
console.log(error.message)
} else {
res.status(200).json(rows);
}
currentConnection.release();
});
}
});
});
What I want is this :
{
"id": "171-15-8966",
"name": "Alif Hasnain",
"course_code": "CSE412,CSE413"
}
But I get the result like this :
[
{
"id": "171-15-8966",
"name": "Alif Hasnain",
"course_code": "CSE412,CSE413"
}
]
Just get the first element of the array before the json transformation:
res.status(200).json(rows[0]);
By default query return the array of rows reflected by the select query. Since your query has single result it returns as array of single object to user.
You can change it to
res.status(200).json(rows[0]);
Please let us know if got better alternate.
Try this, using nested array destructuring
res.status(200).json([[rows]]);
You can read this blog to learn more about ES6 - Destructuring
ES6 - Understanding Destructuring