How to access property on JSON with Arrays and Objects [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 2 years ago.
I have this JSON:
[
{ someTitle: 'NAME OF SomeTitle' },
[
{
id: '7oiqxhRXRqEV0D70G',
photo: 'https://co/image/ab67616d739a3e7d0c38c3af225e4695ce',
jugement: 'GOAl',
Name: 'Some Name.'
}
],
{
token: 'BQAVhYiUweHGTTlIIZHthAKzulZ-DHg'
}
]
This comes from a request I make to my node Server. If I do a console.log(req.body) I get the information above.
So when I try to do console.log(req.body.token) I get undefined.
How can I access the token property then?
The size of the JSON may change , so I can't just access it by index.

Since it is an array of objects, and the element you are looking for is at the 3th position of the array. You need to call it using index = 2 (because index starts with 0).
After that, you can access token property.
const res = [{
someTitle: 'NAME OF SomeTitle'
},
[{
id: '7oiqxhRXRqEV0D70G',
photo: 'https://co/image/ab67616d739a3e7d0c38c3af225e4695ce',
jugement: 'GOAl',
Name: 'Some Name.'
}],
{
token: 'BQAVhYiUweHGTTlIIZHthAKzulZ-DHg'
}
]
console.log(res[2].token)

Check this out
console.log(req.body[2]["token"])
If Array size is not fixed then try this
let req = {
body: [
{ someTitle: "NAME OF SomeTitle" },
[
{
id: "7oiqxhRXRqEV0D70G",
photo: "https://co/image/ab67616d739a3e7d0c38c3af225e4695ce",
jugement: "GOAl",
Name: "Some Name.",
},
],
{
token: "BQAVhYiUweHGTTlIIZHthAKzulZ-DHg",
},
],
};
let data = req.body;
let token = "";
for (let each of data) {
if (each.hasOwnProperty("token")) {
token = each["token"];
break;
}
}
console.log(token)

Related

How to convert mongodb array of object to array of string [duplicate]

This question already has answers here:
How to return only value of a field in mongodb
(6 answers)
Closed 3 months ago.
I am using mongodb with mongoose in NodeJs project.
I want to convert my data array of object to array of string like
[
{
id: '6375ce97e8ec382b8dbf8433',
},
{
id: '638de425cbb676123ad204f6',
},
{
id: '638de425cbb676123ad20509',
},
{
id: '6375ce97e8ec382b8dbf8433',
},
{
id: '638dc4cc48b1de03d0d920b7',
},
{
id: '638de425cbb676123ad204f6',
},
{
id: '6375ce97e8ec382b8dbf8433',
},
];
Convert to
['6375ce97e8ec382b8dbf8433',
'638de425cbb676123ad204f6',
'638de425cbb676123ad20509',
'6375ce97e8ec382b8dbf8433',
'638dc4cc48b1de03d0d920b7',
'638de425cbb676123ad204f6',
'6375ce97e8ec382b8dbf8433']
How I convert my data using mongodb not JavaScript method like, map, filter, find etc
I did not convert the data because lack of mongodb knowledge.
You cannot do this directly within mongodb. The reason is that a document must be an object. Eg, you cannot replace the object with a string. Instead, you have 3 options:
1 - Get the output very close, but you just have to locate the array: https://mongoplayground.net/p/furNa_ezJ5l
db.collection.aggregate([
{
$group: {
_id: null,
data: {
$push: "$$ROOT.id"
}
}
}
])
Gives you:
[
{
"_id": null,
"data": [
"6375ce97e8ec382b8dbf8433",
"638de425cbb676123ad204f6",
"638de425cbb676123ad20509",
"6375ce97e8ec382b8dbf8433",
"638dc4cc48b1de03d0d920b7",
"638de425cbb676123ad204f6",
"6375ce97e8ec382b8dbf8433"
]
}
]
Where the data you want will be:
const stringArray = result[0].data
2 - Use JS after your query
db.collection.find({}).toArray().map( function(u) { return u.id } )
3 - Magic distinct values
Assuming that your values of id are always unique and that you don't want to do any further querying or aggregation, you can ask mongo for the unique ones:
db.collection.distinct('id')
Which should give you:
['6375ce97e8ec382b8dbf8433',
'638de425cbb676123ad204f6',
'638de425cbb676123ad20509',
'6375ce97e8ec382b8dbf8433',
'638dc4cc48b1de03d0d920b7',
'638de425cbb676123ad204f6',
'6375ce97e8ec382b8dbf8433']

How do I populate an array of objects where every object has an array inside of it using response from rest API?

I can't google the right solution for this for about an hour straight,
So I'm getting a response from the API that looks like this:
[
{
"Name": "name1",
"Title": "Name One",
"Children": [
{
"Name": "Name 1.1",
"Title": "Name one point one"
},
]
And I need it to fit this kind of "mold" for the data to fit in:
{
title: 'Name One',
value: 'name1',
key: '1',
children: [
{
title: 'Name one point one',
value: 'Name 1.1',
key: 'key1',
},
I am trying to achieve this using a foreach but It's not working as intended because I need to do this all in one instance of a foreach.
Here's what I gave a go to(vue2):
created() {
getData().then(response => {
const formattedResponse = []
response.forEach((el, key) => {
formattedResponse.title = response.Title
formattedResponse.name = response.Name
formattedResponse.children = response.Children
})
})
Use map over the main array and use destructuring assignment to extract the properties by key, and relabel them, and then do exactly the same with the children array. Then return the updated array of objects.
const data=[{Name:"name1",Title:"Name One",Children:[{Name:"Name 1.1",Title:"Name one point one"}]},{Name:"name2",Title:"Name Two",Children:[{Name:"Name 1.2",Title:"Name one point two"}]}];
const result = data.map((obj, key) => {
const { Title: title, Name: value } = obj;
const children = obj.Children.map(obj => {
const { Title: title, Name: value } = obj;
return { title, value, key: (key + 1).toString() };
});
return { title, value, children };
});
console.log(result);
Your API response is JSON. All you need to do is:
var resp=JSON.parse(API response);

Destructing assignment javascript doesnt work [duplicate]

This question already has answers here:
How to delete property from spread operator?
(9 answers)
Closed 2 years ago.
I've tried to destruct a json. This is the original:
const shoppingLists = [
{
id: 0,
name: "empty shopppinglist",
location: "",
targetDate: "",
priority: "",
isFinished: false,
items: [{
name: ""
}]
},
{
id: 1,
name: "full shopppinglist",
location: "migros",
targetDate: "",
priority: "1",
isFinished: true,
items: [{
name: "apfel"
}]
}}
I need now just the lists with the elements but without the items list
const { id, name, location, targetDate, priority, isFinished } = shoppingLists
res.send(shoppingLists)
But when I receive/log shoppingLists, I always get again the whole object.
I've also tried with items, ...rest but same result at the end, what am I doing wrong?
You should change your syntax since shoppingLists is an array:
const { id, name, location, targetDate, priority, isFinished } = shoppingLists[0]
Also, if you want to remove an item from an array you definitely need to use splice or if you want to remove the first element and then get its value as return then you should use shift.
const { id, name, location, targetDate, priority, isFinished } = shoppingLists.shift()

Count the length of messages from the same user [duplicate]

This question already has answers here:
Loop through array of objects and return sum of each total values by object element id
(4 answers)
Closed 4 years ago.
I have an array called users that includes an object, which looks like this:
'user': {
'name': name,
'msg': msg
}
It is possible that in that array a user ist listed multiple times.
I would like to count the length of all his messages (msg).
This is how I tried it:
score = [];
for (i of users) {
for (s of score) {
if (s.name === i.user.name) {
score.push({
'name': i.user.name,
'counter': i.user.msg.length
});
}
else {
s.counter = s.counter + i.user.msg.length;
}
}
}
The array score which also includes an object should only include unique users. So they shouldn't be listed twice.
Anyway, that doesn't work and I am not very happy with my code, because there must be a better and an easier solution.
You can use reduce to convert scores into a map of all the unique values.
Once you have that map, if you want you can convert that into an array.
const users = [
{
name: 'user1',
msg: 'hello',
},
{
name: 'user1',
msg: 'hello2',
},
{
name: 'user2',
msg: 'world',
},
{
name: 'user2',
msg: 'world2',
},
{
name: 'user3',
msg: 'foo',
},
];
const scores = users.reduce((scores, {name, msg}) => {
if (!scores[name]) {
scores[name] = { name, counter: 0 };
}
scores[name].counter += msg.length;
return scores;
}, {});
// Now convert to an array if you want
console.log(Object.entries(scores));
You could use object instead of array for score and use user.name as key:
const score = {};
for (const user of users) {
if (score[user.name]) {
score[user.name].counter += user.msg.length;
} else {
score[user.name] = {
name: user.name,
counter: user.msg.length,
}
}
}

How to loop over an array within a JavaScript object?

Very new to JavaScript objects, so I am not to sure how to go about doing this.
Within my object, I have an array called myArray. I am attempting to loop over it to print out everything on the page. Usually there is a a lot more data within the object, but it has been removed for this example.
This is my object:
var data = [
{
myArray:
{
name: 'name1',
code: 'code1',
data: {
date: '20-Apr-2014',
signal: 'signal1'
}
},
{
name: 'name2',
code: 'code2',
data: {
date: '21-Apr-2014',
signal: 'signal2'
}
}
}
]
This is my iteration code:
var arrayLength = data.myArray.length - 1;
for (var i = 0; i <= arrayLength; i++) {
var name = data.myArray[i].name;
console.log(name);
}
My code above should produce the results in the console name1 and name2. However, I am getting an error of Cannot read property 'length' of undefined.
How can I change my above code to do this?
Your object should use brackets for the array:
var data = {
myArray: [
{
name: 'name1',
code: 'code1',
data: {
date: '20-Apr-2014',
signal: 'signal1'
}
},
{
name: 'name2',
code: 'code2',
data: {
date: '21-Apr-2014',
signal: 'signal2'
}
}
]
}
I've also removed the outermost brackets, since it would appear from your question that your intent was to have a single array inside an object, and not an array of arrays.
With the object above, your iteration code will work fine.

Categories

Resources