This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I'm attempting to use Javascript objects to work with some data. Here is the object itself (parsed from JSON) which is defined as accounts:
{
startIndex: 0,
pageSize: 20,
pageCount: 1,
totalCount: 1,
items: [
{
id: 123456,
emailAddress: 'test#test.com',
userName: 'test#test.com',
firstName: 'John',
lastName: 'Hancock',
customerSet: 'default',
commerceSummary: [
Object
],
contacts: [
Object
],
userId: '92834439c29389fj292',
notes: [
],
attributes: [
Object
],
segments: [
Object
],
taxExempt: false,
externalId: '2100010368',
isAnonymous: false,
auditInfo: [
Object
],
isLocked: false,
isActive: true,
hasExternalPassword: false,
customerSinceDate: 2016-06-23T18: 26: 46.000Z
}
]
}
While I can retrieve accounts.items without issue, I'm having some trouble retrieving individual values such as id or emailAddress from the item itself. Doing accounts.items[id] or accounts.items[emailAddress] does not work but I believe it's due to the fact that items can be more than 1 so I should be specifying the "first result" for items from that list. If that is the case, how do I retrieve the emailAddress or id for the first items array? The desired result from the above JSON object should be "123456" if id and "test#test.com" if email. Thanks in advance.
Your items is an array. You have to fetch data from it by indexes (like items[0]). If you are looking for an item, with their properties, use Array.find method.
The find method executes the callback function once for each element
present in the array until it finds one where callback returns a true
value. If such an element is found, find immediately returns the value
of that element. Otherwise, find returns undefined. callback is
invoked only for indexes of the array which have assigned values; it
is not invoked for indexes which have been deleted or which have never
been assigned values.
var accounts = {
startIndex: 0,
pageSize: 20,
pageCount: 1,
totalCount: 1,
items: [
{
id: 123456,
emailAddress: 'test#test.com',
userName: 'test#test.com',
firstName: 'John',
lastName: 'Hancock',
customerSet: 'default'
}
]
};
var sampleAccount = accounts.items.find(function (item) {
return item.id == 123456;
});
if (sampleAccount) {
console.log(sampleAccount.emailAddress);
}
You are right, first you need to reference the first element of the array. Then you can query its properties.
For example, to get the ID and email address of the first item you would write
accounts.items[0].id
accounts.items[0].emailAddress
Arrays elements start at index 0 in JavaScript, so the first element of the array has index 0, the second 1, and so on.
Items is an array and emailAddress is a Key, then you can get the value using:
accounts.items[0].emailAddress
Related
I'm trying to find the cleanest way to implement a filter to an array of objects depending on a string keyword. I need to return those objects whose only specific properties contains the string value.
Let's say I have the following array of objects:
const products = [
{
name: 'car',
price: 100,
image: 'someurl'
email: 'car#car.car'
available: true,
},
{
name: 'phone',
price: 200,
image: 'someurl'
email: 'phone#phone.phone'
available: false,
},
{
name: 'bottle',
price: 300,
image: 'someurl'
email: 'bottle#bottle.bottle'
available: true,
},
];
As mentioned here: Filter array of objects whose any properties contains a value
One of the cleanest way to match any value in an array of objects whose properties have different types would be:
function filterByValue(array, string) {
return array.filter(o =>
Object.keys(o).some(k => String(o[k]).toLowerCase().includes(string.toLowerCase())));
}
This filterByValue function will return those objects whose any properties match the string value.
However, I'd like to add some conditions, so it only iterates and look for some match at "name", "price" and "email" properties, not looking at "image" and "available" properties.
Make an array of the properties to look at, and look at them instead of using Object.keys.
const propsToCheck = ['name', 'price', 'email'];
function filterByValue(array, string) {
return array.filter(o =>
propsToCheck.some(k => String(o[k]).toLowerCase().includes(string.toLowerCase())
)
);
}
I have an array as such:
arr = {
name: 1,
address: 1,
phone: 2,
email: 5,
};
I want to be able to add further information to this array, eg:
arr = {
name: 1 true,
address: 1 false,
phone: 2 true,
email: 5 true,
};
I've tried a few different things like:
arr.email[2] = true;
With no results (or errors).
Is there a way to do this? Or a better way of handling this issue?
I'm not entirely certain what you're going for here since you mention wanting an array ([]) but what you've shown in your question is an object ({}), but if I'm reading right you can accomplish this with an object where each key holds an array of values. That would look like:
const obj = {
name: [1],
address: [1],
phone: [2],
email: [5],
};
obj.email.push(true);
obj.email.push("whatever");
console.log(obj)
console.log(obj.email[1])
console.log(obj.email[2])
So obj is an object, but name, address, phone, and email are all arrays which you can extend as needed with array methods.
Original data structure doesn't allow you to add data the way you want. So you have to create the object with needed data structure at first. After this the original data should be moved to the new object and only after this you can add some new data.
newObj.name.push(origObj.name,true,"something1","something2");
newObj.address.push(origObj.address,false);
newObj.phone.push(origObj.phone,true);
newObj.email.push(origObj.email,true);
output
{
"name":[1,true,"something1","something2"],
"address":[1,false],
"phone":[2,true],
"email":[5,true]
}
original object
var origObj = {
name: 1,
address: 1,
phone: 2,
email: 5
};
new object
var newObj = {
name: [],
address: [],
phone:[],
email: []
};
You would need to assign a variable to your array and call a function...that way, each element could be classified (boolean, string, integer, etc.) For example,
const fruit = ['banana', 'apple', 'pear'];
console.log(fruit);
Simply trying to emit an array of data.
Example of an array I am emitting:
[
{
userid: 1,
usertag: "random"
}
name: "cool",
age: 10
]
The server receives it but only returns the object inside the array.
So in this example it only returns:
[
{
userid: 1,
usertag: "random"
}
]
So I am missing the name value and age value.
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()
I wonder how I could insert array of objects to Mongo collection "root-level documents" with own pre-defined _id values.
I have tried db.MyCollection.insert(array); but it creates nested documents under one single generated _id in MongoDB.
var array = [
{ _id: 'rg8nsoqsxhpNYho2N',
goals: 0,
assists: 1,
total: 1 },
{ _id: 'yKMx6sHQboL5m8Lqx',
goals: 0,
assists: 1,
total: 1 }];
db.MyCollection.insert(array);
What I want
db.collection.insertMany() is what you need (supported from 3.2):
db.users.insertMany(
[
{ name: "bob", age: 42, status: "A", },
{ name: "ahn", age: 22, status: "A", },
{ name: "xi", age: 34, status: "D", }
]
)
output:
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("57d6c1d02e9af409e0553dff"),
ObjectId("57d6c1d02323d119e0b3c0e8"),
ObjectId("57d6c1d22323d119e0b3c16c")
]
}
Why not iterate over the array objects, and insert them one at a time?
array.forEach((item) => db.MyCollection.insert(item));
Go through this Link To get Exact Outcome the way you want:
https://docs.mongodb.org/manual/tutorial/insert-documents/#insert-a-document
You can use MongoDB Bulk to insert multiple document in one single call to the database.
First iterate over your array and call the bulk method for each item:
bulk.insert(item)
After the loop, call execute:
bulk.execute()
Take a look at the refereed documentation to learn more.