I'm trying to update an array (Array name is "Variables" please refer the attached screenshot) which presents inside an Object, so I want to update that array if there is word called "placeholder" in alertMessage(it's a different property presents in the same Object)
I'd appreciate any help on how to update this array in question, I tried using pop method but it didn't go as planned and I've attached screenshots of the Objects for reference
You can retrieve the string placeholder like this data['alertMessage']['en_US']['all'] and then use a conditional statement to make changes to the array inside the data object.
let data = {
alertOne: '',
alertTwo: '',
alertMessage: {
en_US: {all: 'placeholder'}
},
variables: [
{id: 0, uuid: '123'},
{id: 1, uuid: '223'},
{id: 2, uuid: '323'}
]
}
let all = data['alertMessage']['en_US']['all']
// if condition is met add a new object to the array
if(all === 'placeholder'){
data.variables = [...data.variables, {id: 3, uuid: '423'}]
}
console.log(data)
Related
Im completely lost. This is some test code I use to print a specific key of an object, then im printing the entire object.
console.log(docs[0].mc_ign);
console.log(docs[0]);
Now this is the output I see on the console:
The__TxT
{
id: 0,
status: 1,
testing: false,
_id: 5dbc17eb20b3a8594d569570,
timestamp: 2019-11-01T11:32:59.380Z,
mc_uuid: 'dac89e44d1024f3b810478ed62d209a1',
discord_id: '653029505457586176',
email_address: 'gut97930#eveav.com',
country: 'Germany',
birth_month: 3,
birth_year: 1943,
about_me: 'about me text',
motivation: 'motivation text',
build_images: '',
publish_about_me: true,
publish_age: false,
publish_country: true,
__v: 0
}
Where is the mc_ign key?
The object itself comes from mongoose, the missing key is added by me after the fact:
docs[i].mc_ign = mc_ign;
I tried logging the entire object before and after I add the key and assign the value. They are both the same.
What am I missing? Why can I read the value out, but cant see it?
It is mongoose document object. To achieve what you want do the following.
docs[0] = docs[0].toObject();
docs[0].mc_ign = "stuff";
console.log(docs[0])
.toObject() convert it to plain JS object.
Im trying to separate out the functionality of my model and the data so ive created a separate json file with a basic table
when my model builds it creates an object and i need it to create a value in it based on a value coming in:
{
"1":"apple",
"2":"banana",
"3":"orange",
"4":"grape"
}
async save (xmlOrder) {
let customerOrder = {
ID: xmlOrder.ID,
Name: xmlOrder.Name ,
ItemCode: xmlOrder.ItemCode ,
Fruit: (This set by referencing the json, based on the Item code coming in above)enter code here
}
You can import that json object in file where you're having your model, than based on input to function you can get value out of object.
let obj = {"1":"apple","2":"banana","3":"orange","4":"grape"}
function save (xmlOrder) {
let customerOrder = {
ID: xmlOrder.ID,
Name: xmlOrder.Name ,
ItemCode: xmlOrder.ItemCode ,
Fruit: obj[xmlOrder.ItemCode] || 'Not in list',
}
return customerOrder
}
console.log(save({ID:33,Name:'Name',ItemCode:'2'}))
console.log(save({ID:303,Name:'Name1',ItemCode:'21'}))
I'm writing a route in Express (Node.js) in which i pull some data from mongoose. Let's say that at some some point I need to compare if employee._id is in array of bad employees id::
let employees = await EmployeeModel.find().exec();
employees.forEach(function (employee) {
if (arrayOfBadEmployees.indexOf(employee._id) !== -1) {
employee.isBad = true;
}
});
console.log(employees);
console.log(employees[0].isBad);
and here's my output:
[ { __v: 0, name: 'Employee X', _id: 1 },
{ __v: 0, name: 'Employee Y', _id: 3 },
{ __v: 0, name: 'Employee Z', _id: 5 } ]
true
So when I can't see 'isBad' property when I console.log the whole array/object, but this property is still there? When i check with propertyIsEnumerable('isBad') it says true.
Mongoose, by default, returns an instance of MongooseDocument, which doesn't expose your data directly and adds convenience methods like populate or save
You can use the lean option to get raw objects instead.
MongooseDocument also exposes a toObject function if you need to get editable documents.
Javascript now implements Object.observe and Array.observe, however I cannot seem to find a way to merge the functionality.
What I am trying to do is to have an array of objects. When any property of one of the objects changes, I would like to be notified.
Object.observe allows me to be notified when a property of a specific object changes.
Array.observe allows me to be notified when an array level change occurs.
Unless I specifically observe each element of an array, I have no way to know when a specific element property changes.
For example:
var model = [
{
data: 'Buy some Milk',
completed: false
},
{
data: 'Eat some Food',
completed: false
},
{
data: 'Sleep in a Bed',
completed: false
},
{
data: 'Make Love not War',
completed: false
}
];
Array.observe(model, function(changeRecords) {
console.log('Array observe', changeRecords);
});
model[0].data = 'Teach Me to code';
model[1].completed = true;
model.splice(1,1);
model.push({data: "It's a new one!",completed: true});
gives a console output of:
Array observe [Object, Object]
0: Object
addedCount: 0
index: 1
object: Array[4]
removed: Array[1]
type: "splice"
__proto__: Object
1: Object
addedCount: 1
index: 3
object: Array[4]
removed: Array[0]
type: "splice"
__proto__: Object
length: 2
__proto__: Array[0]
These two notifications relate specifically to:
model.splice(1,1);
and
model.push({data: "It's a new one!",completed: true});
but completely ignore
model[0].data = 'Teach Me to code';
and
model[1].completed = true;
Is there a way to observe every change, no matter whether it is an array level or object level change?
I know there are libraries that may be able to do this for me, however I would like to understand how to implement this directly in my own code.
EDIT: OK, So it seems I wasn't missing any magic functionality, and the only true option is to observe the individual elements of the array.
So to expand upon the original question, what is the most efficient method of adapting arrays to handle element observations?
Array observe observes array changes! You need to observe each object inside Array too using Object.Observe!
See this
function ObserveMyArray(myArray){
var arr=myArray||[];
for(var i=0;i<arr.length;i++){
var item=arr[i];
Object.observe(item , function(changes){
changes.forEach(function(change) {
console.log(change.type, change.name, change.oldValue);
});
});
}
Array.observe(arr, function(changeRecords) {
console.log('Array observe', changeRecords);
});
}
I need to access the "State" value from the following array --
data =
{
Images:
[
{
ProductCodes: [],
BlockDeviceMappings: [Object],
Tags: [],
ImageId: 'ami-75301c',
ImageLocation: '54696560/Test Image 3',
State: 'available',
VirtualizationType: 'pavirtul',
Hypervisor: 'xen'
}
],
requestId: '2eb809d3-7f82-4142-b5d1-6af3'
}
When I try data.Images["State"] or data.Images.State I get undefined.
Thanks
Images maps to an array which stores objects, so you have to specify the index of the item you want. Try data.images[0]["State"].
You can access like this:
data.Images[0].State
Or even:
data.Images[0]['State']
Access the state with data.image[0].state. Your method was wrong because inside the image, you need an index within the two square bracket, the image property is an array.