Adding same property:value pair to multiple objects in array - javascript

I have two arrays, which are almost identical in structure, except for one has a property:value pair on every object, and the other doesn't.
Newcastle Array (with clubCode property)
[
{"clubCode": "newcastle-united",
"firstName": "Tim",
"lastName": "Krul",
"position": "gk"},
{"clubCode": "newcastle-united",
"firstName": "Rob",
"lastName": "Elliot",
"position": "gk"}
]
Arsenal Array (without clubCode property)
[
{"firstName": "Petr",
"lastName": "Cech",
"position": "gk",
{"firstName": "David",
"lastName": "Ospina",
"position": "gk"}
]
Is it possible to push() the clubCode property to every object within the Arsenal array, so I don't have to manually add it to every single one?
...so each object starts with "clubCode": "arsenal".
Or if there is any other solution I'd love to hear it.
Any help will be appreciated. Thanks in advance.

You can use Array.prototype.forEach over your data structure.
var x = [
{"firstName": "Petr",
"lastName": "Cech",
"position": "gk",
},
{"firstName": "David",
"lastName": "Ospina",
"position": "gk"}
];
x.forEach(function(e){e.clubCode='arsenal';})

Try to use Array.prototype.map() at this context,
arsenalArray = arsenalArray.map(function(itm){
return (itm.clubCode = "arsenal", itm);
});
DEMO

$scope.ar1 = [
{"clubCode": "newcastle-united",
"firstName": "Tim",
"lastName": "Krul",
"position": "gk"},
{"clubCode": "newcastle-united",
"firstName": "Rob",
"lastName": "Elliot",
"position": "gk"}
];
$scope.ar1.forEach(function (value) {
value.clubCode = "newcastle-united";
});
console.log($scope.ar1);

Its very easy using lodash.js
_.assign(arsenalArray, { clubCode: "arsenal" });

Related

JSONPath getting Error when square brackets inside of string

kI have a problem with the library https://github.com/JSONPath-Plus/JSONPath at the latest version.
Example:
{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"phoneNumbers [1]": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
]
}
Now i want to get "phoneNumbers [1]" with
path: $..['phoneNumbers [1]']
Here is a Demo Page for testing: https://jsonpath-plus.github.io/JSONPath/demo/
That did not work because of the square brackets inside of the String.
Do anyone know how to solve this Problem.
I have a lot of Json Objects containing strings with square brackets, so if there is a solution not only for a specific case.
Is there any option to escape characters so that the problem will be solved?
The json Object above is only a Example Code to describe the Problem.
The Problem also occurs when only using JSONPath so it is not limited to that Library.
https://jsonpath.com/
This appears to be a bug in JSONPath-Plus. The jsonpath library can handle it.
const data = JSON.parse(`{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"phoneNumbers [1]": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
]
}`);
const result = jsonpath.query(data, "$..['phoneNumbers [1]']");
console.log(result);
<script src="https://unpkg.com/jsonpath#1.1.1/jsonpath.js"></script>
There's not much you can do about this beyond:
Changing your data structure
Changing your library
Filing a bug report
There is a workaround you can use only with jsonpath-plus
$[?(#property == "phoneNumbers [1]")]

Does reading file in node.js guarantee the order of items

In my node.js application I have test data file that I read to populate some inputs. The test file contains an array of objects.
I use for reading:
data = fs.readFileSync(fileName, "utf8");
My test file:
[
{
"firstname": "John",
"lastname": "Doe",
"birthdate": "01/01/1970"
},
{
"firstname": "El",
"lastname": "Maestro",
"birthdate": "01/01/1989",
"isDeleted": true
}
]
So the question is - when I read this file is it guaranteed that I will always get object with name "John" at index 0, and "El" at index 1?
Arrays always ensures order in JS
BUT
Keys inside objects doesnot ensure order in JS, they are 'unordered key value pair'
To answer your question:
when I read this file is it guaranteed that I will always get object with name "John" at index 0, and "El" at index 1
yes
BUT
The keys in the resulting object can be unordered, eg: it can be
{
"firstname": "John",
"lastname": "Doe",
"birthdate": "01/01/1970"
}
or
{
"lastname": "Doe",
"birthdate": "01/01/1970",
"firstname": "John"
}
etc...

Javascript Object and Classes

I have a code snippet of JavaScript:
mf.profile.push({
"Site": {
"Name": "Jack Montana",
"Identity": 61026032,
"Email": "jack#gmail.com",
"Phone": "+14155551234",
"Gender": "M",
}
});
mf.event.push("Product viewed", {
"Product name": "Casio Chronograph Watch",
"Category": "Mens Accessories",
"Price": 59.99,
"Date": new Date()
});
Now my question is what does mf.profile.push or mf.event.push signify?
Is mf an object and profile a function? or both are classes and push is a function?
what does mf.profile.push or mf.event.push signify
The mf variable is an Object literal and the profile/event are properties (may of type array) belongs to this object.
The push() is a method that will add the items passed as parameters to those attributes.

How to iterate through following compex JSON data and access its all values including nested?

I have following JSON data but I don't know how to iterate through it and read its all values:
var students = {
"student1": {
"first_name": "John",
"last_name": "Smith",
"age": 24,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
},
"student2": {
"first_name": "David",
"last_name": "Silva",
"age": 22,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
}
};
I would like to use following methods to do the needful:
Using for in loop
Using simple for loop
Using $.each in jQuery
I will prefer to display above values in <ul> <li> nicely formatted.
Also, please suggest me what will be look of above JSON data if I put it in an external .json file?
You can use for in loop to iterate over the object, as it iterates over the properties of an object in an arbitrary order, and needs to use .hasOwnProperty, unless inherited properties want to be shown.
Now about accessing the object, let's say I have a JSON like
var myJson={name:"john",age:22,email:"email#domain.com"};
and I need to access the value of name i would simply use . operator using the myJson variable i.e console.log(myJson.name) will output john. because it will be treated as an object, now if I make a little change and make the object like below
var myJson=[{name:"john",age:22,email:"email#domain.com"}];
now if you try to access the value of the property name with the same statement above you will get undefined because the [] will now treat it as an object(JSON) with an array of 1 person or a JSON Array, now if you access it like console.log(myJson[0].name) it will print john in console what if there was more than one person in the array? then it will look like following
var myJson=[
{name:"john",age:22,email:"john#domain.com"},
{name:"nash",age:25,email:"nash#domain.com"}
];
console.log(myJson[0].name) will print john and console.log(myJson[1].name) will print nash so as I mentioned in the start that you should use for in loop for iterating over an object and if we want to print all the names of the person in the JSON Array it will be like.
for(var person in myJson){
console.log(myJson[person].name, myJson[person].age, myJson[person].email);
}
it will output in the console like below
john, 22, john#domain.com
nash, 25, nash#domain.com
I have tried to keep it simple so that you understand you can look into for in and hasOwnProperty, in your case you have a nested object in which property/key subject is an array so if I want to access the first_name of student1 i will write students.student1.first_name and if I want to print the name of the first subject of student1 I will write students.student1.subject[0].name
Below is a sample script to print all the students along with their subjects and marks and personal information since you JSON is nested I am using a nested for in, although Nested iterations are not necessarily a bad thing, even many well-known algorithms rely on them. But you have to be extremely cautious what you execute in the in the nested loops.
For the sake of understanding and keeping the given example of json object, i am using the same to make a snippet. Hope it helps you out
var students = {
"student1": {
"first_name": "John",
"last_name": "Smith",
"age": 24,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
},
"student2": {
"first_name": "David",
"last_name": "Silva",
"age": 22,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
}
};
$("#print").on('click', function() {
for (var student in students) {
console.log(students[student].first_name + '-' + students[student].last_name);
for (var subject in students[student].subject) {
console.log(students[student].subject[subject].name, students[student].subject[subject].marks);
}
}
setTimeout('console.clear()', 5000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="print" value="print-now">

Delete an object in Scope

This question might not even be related to angularjs and the solution could be plain old js or jquery. But that is what i what to find out.
I want to implement a delete functionality for a particular user and i am wondering if there is a easier way to do this in angularjs or should it be plain old JS?
i have a fairly complex object for eg (going up to 4 levels):
{
"Department": [
{
"Name": "Accounting",
"users": [
{
"id": "1",
"firstName": "John",
"lastName": "Doe",
"age": 23
},
{
"id": "2",
"firstName": "Mary",
"lastName": "Smith",
"age": 32
}
]
},
{
"Name": "Sales",
"users": [
{
"id": "3",
"firstName": "Sally",
"lastName": "Green",
"age": 27
},
{
"id": "4",
"firstName": "Jim",
"lastName": "Galley",
"age": 41
}
]
}
]
}
this is displayed in a ng-repeat where we should Department and username. If I want to delete a particular user i make an api call and on success of it, I want to delete that object. so i have a js method like this
function DeleteUser(user) {
$.each(ctrl.UserData, function(index, value) {
var filteredPeople = value.filter((item) => item.id !== user.id);
});
The question I have is, if i want to delete this object is there any easier way to delete from model since i have the object here or i have to do the classic jquery way of using like $.grep or filter to iterate through each object and match by id and then delete it?
Presumably, you're iterating over the departments (accounting, sales) in your template, and then over the users in that department.
So you could have, in your template:
<button ng-click="deleteUser(user, department)">...</button>
And the method could thus be as simple as
$scope.deleteUser = function(user, department) {
// delete user from backend, then
department.users.splice(departments.users.indexOf(user), 1);
}
If you really don't want to pass the department, then loop over the departments, and use the above if departments.users.indexOf(user) returns a value that is >= 0.

Categories