Object Splicing within Array not giving correct result - javascript

In my application i want to splice objects from an array upon matching, I am using lodash function for splicing like as shown below, unfortunately the json is not splicing correctly,
Working Demo
Can anyone give me some suggestion for this issue
var arr = [{
name: 'Jack',
id: 125
}, {
name: 'Jack',
id: 125
}];
var result = _.without(arr, _.findWhere(arr, {name: 'Jack'}));
console.log(JSON.stringify(result));
Expected result
[]
Actual Result
[{"name":"Jack","id":125}]
Update 1
Even using normal JavaScript way also giving the same output
for(var i = 0; i < arr.length; i++) {
var obj = arr[i];
if(obj.name === 'Jack') {
arr.splice(i, 1);
}
}

#1
var arr = [{
name: 'Jack',
id: 125
}, {
name: 'Jack',
id: 125
}];
var result = _.rest(arr, function (el) {
return el.name === 'Jack';
});
console.log(JSON.stringify(result)); // "[]"
#2
var arr = [{
name: 'Jack',
id: 125
}, {
name: 'Jack',
id: 125
}, {
name: 'foo',
id: 124
}];
var result = _.rest(arr, function (e) {
return e.name === 'Jack';
});
console.log(JSON.stringify(result)); // "[{\"name\":\"foo\",\"id\":124}]"
// 3 also you can use _.filter if you do not want slice of array...
var result = _.filter(arr, function (e) {
return e.name !== 'Jack';
});
console.log(JSON.stringify(result)); // "[{\"name\":\"foo\",\"id\":124}]"

_.findWhere returns only the first matching element. So that you can use _.difference and _.filter or _.rest to do the task
_.difference(arr, _.filter(arr,function(d){ return d.name = 'Jack' }));
You can implement the same using pure javascript using the code below.
for(var i = 0; i < arr.length; i++) {
var obj = arr[i];
if(obj.name === 'Jack') {
arr.splice(i, 1);
i--; // Splicing of elements will cause shifting of indices in the array
}
}

Related

JavaScript - Altering keys when criteria met

I want to write a function that takes an array of objects as an argument. If an object in the array contains the key "name," I want to change that key to "title." I then want to return an updated version of the array of objects with all of the keys changed.
This is my attempt at doing this. It's not doing what I want it to.
const people = [{age: 32},{name: 'bob'},{name: 'jack', age: 3}];
function nameToTitle(arr){
let result = [];
for(let i = 0; i < arr.length; i++){
if(arr[i].name){
let newObj = {};
for(let x in arr[i]){
if(arr[i][x] === 'name'){
newObj['title'] = arr[i][x];
}
else {
newObj[x] = arr[i][x];
}
}
result.push(newObj);
}
else {
result.push(arr[i])
}
}
return result;
}
console.log(nameToTitle(people));
This above code returns this:
[ { age: 32 }, { name: 'bob' }, { name: 'jack', age: 3 } ]
=> undefined
It doesn't change the name key to "title."
The code below should work for your use case. Note that I've changed people to a mutable variable (not a const any more). Essentially all this does is iterate over each dictionary in your array, if it finds a dictionary with the "name" key it sets a "title" key with the same value and then deletes the "name" key.
var people = [{age: 32}, {name: 'bob'}, {name: 'jack', age: 3}];
for (var i = 0; i < people.length; i++) {
if (people[i].hasOwnProperty("name")) {
people[i]["title"] = people[i]["name"];
delete people[i]["name"];
}
}
console.log(people);
You are very close, your if-condition is checking the value of your object rather than the key. So all you need to do is change:
if(arr[i][x] === 'name') // 'bob' === 'name' for {name: 'bob'}
to:
if(x === 'name') // 'name' === 'name' for {name: 'bob'}
Because the value of x in for(let x in arr[i]) is the key value that you are iterating.
const people = [{age: 32},{name: 'bob'},{name: 'jack', age: 3}];
function nameToTitle(arr){
let result = [];
for(let i = 0; i < arr.length; i++){
if(arr[i].name){
let newObj = {};
for(let x in arr[i]){
if(x === 'name'){
newObj['title'] = arr[i][x];
}
else {
newObj[x] = arr[i][x];
}
}
result.push(newObj);
}
else {
result.push(arr[i])
}
}
return result;
}
console.log(nameToTitle(people));
you can map over the objects in the array and modify objects that have the name property as shown below
peoples.map(people => {
if(people.hasOwnProperty('name')) {
let title = people.name;
delete people.name;
return Object.assign({}, people, {title: title});
}
return people;
})
const people = [{age: 32},{name: 'bob'},{name: 'jack', age: 3}];
// Copy all properties. If key is 'name' change it to 'title'
const copyObjectWithTitle = obj =>
Object.keys(obj).reduce((objAcc, key) => {
const value = obj[key];
return Object.assign({}, objAcc, key === 'name' ? { title: value} : { [key]: value });
}, {})
// Map over the list. If the object has the key 'name' return a copy with the key 'title'
const nameToTitle = (list) => list.map(obj => obj.hasOwnProperty('name') ? copyObjectWithTitle(obj) : Object.assign({}, obj))
const updatedPeople = nameToTitle(people);
I would do this, if you just want to change the name property to title:
function nameToTitle(objsArray){
var s = objsArray.slice(), a; // make a copy
for(var i in s){
a = s[i];
if(a.name){
s[i].title = a.name; delete s[i].name;
}
}
return s;
}
var objsArray = [{age:32},{name:'bob'},{name:'jack', age:3}];
console.log(nameToTitle(objsArray));
This might get downvoted a bit, but just for fun :]
const people = [{age: 32}, {name: 'bob'}, {name: 'jack', age: 3}];
const result = eval(JSON.stringify(people).replace(/\bname\b/g, 'title'));
console.log(result);

Trying to avoid duplicates when creating new array from comparing value of two others

I have an app where I need to create a new array by pushing values from two other arrays after comparing what values in one array exist in another.
Example:
From these two arrays...
sel[1,4];
bus[1,2,3,4,5,6];
The desired result is a new object array which will populate a repeater of checkboxes in my view...
newList[{1:true},{2:false},{3:false},{4:true},{5:false},{6:false}];
The problem I'm running into, is that my code is creating duplicates and I'm not seeing why.
Here is my code:
var newList = [];
var bus = self.businesses;
var sel = self.campaign.data.businesses;
for( var b = 0; b < bus.length; b++ ){
if(sel.length > -1){
for( var s = 0; s < sel.length; s++){
if( bus[b]._id === sel[s].business_id){
newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':true});
} else {
newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':false});
}
}
} else {
console.log('hit else statement');
newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':false});
}
}
I need fresh eyes on this as it looks correct to me... but obviously I'm missing something. :-)
Your code produces duplicates because you push selected: false objects into your newList every time the inner loop is run and the ids don't match:
for( var s = 0; s < sel.length; s++){
if( bus[b]._id === sel[s].business_id){
newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':true});
} else {
// THIS LINE CAUSES THE DUPLICATES:
newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':false});
}
}
To fix your code, move this line out of the inner loop into the outer loop below and add a continue outer; to the inner loop's if body. Then you need to place the outer label directly in front of the outer loop: outer: for( var b = 0; b < bus.length; b++ ) ....
However, I recommend a simpler implementation as follows:
let selection = [{_id: 1, business_name: 'A'}];
let businesses = [{_id: 1, business_name: 'A'}, {_id: 2, business_name: 'B'}];
let result = businesses.map(business => ({
'business_id': business._id,
'name': business.business_name,
'selected': selection.some(selected => business._id == selected._id)
}));
console.log(result);
Appendix: Same implementation with traditional functions:
var selection = [{_id: 1, business_name: 'A'}];
var businesses = [{_id: 1, business_name: 'A'}, {_id: 2, business_name: 'B'}];
var result = businesses.map(function(business) {
return {
'business_id': business._id,
'name': business.business_name,
'selected': selection.some(function(selected) { return business._id == selected._id })
};
});
console.log(result);
I suggest to use a different approach by using an object for sel and the just iterate bus for the new array with the values.
function getArray(items, selected) {
var hash = Object.create(null);
selected.forEach(function (a) {
hash[a] = true;
});
return items.map(function (a) {
var temp = {};
temp[a] = hash[a] || false;
return temp;
});
}
console.log(getArray([1, 2, 3, 4, 5, 6], [1, 4]));
ES6 with Set
function getArray(items, selected) {
return items.map((s => a => ({ [a]: s.has(a) }))(new Set(selected)));
}
console.log(getArray([1, 2, 3, 4, 5, 6], [1, 4]));
You can use map() method on bus array and check if current value exists in sel array using includes().
var sel = [1,4];
var bus = [1,2,3,4,5,6];
var result = bus.map(e => ({[e] : sel.includes(e)}))
console.log(result)
This combines both Nina Scholz elegant ES6 approach with le_m's more specific solution to give you something that is shorter, versatile, and repurposable.
function getArray(items, selected, [...id] = selected.map(selector => selector._id)) {
return [items.map((s => a => ({
[a._id + a.business_name]: s.has(a._id)
}))(new Set(id)))];
}
console.log(...getArray([{
_id: 1,
business_name: 'A'
}, {
_id: 2,
business_name: 'B'
}, {
_id: 3,
business_name: 'C'
}, {
_id: 4,
business_name: 'D'
}, {
_id: 5,
business_name: 'E'
}, {
_id: 6,
business_name: 'F'
}], [{
_id: 1,
business_name: 'A'
}, {
_id: 2,
business_name: 'B'
}]));

How can I return an object out of an array? [duplicate]

This question already has answers here:
Get JavaScript object from array of objects by value of property [duplicate]
(17 answers)
Closed 6 years ago.
I have an array of objects and I wanted to search through each object and check if the data matches a given value and I want to return the object out of the array and if it is not found then I have to return undefined.
This is what I have so far:
var data = [{
id: 1,
firstName: 'John',
lastName: 'Smith'
}, {
id: 2,
firstName: 'Jane',
lastName: 'Smith'
}, {
id: 3,
firstName: 'John',
lastName: 'Doe'
}];
var asf[] = data[0];
return asf;
I'm trying to return the object if the condition in if else statement matches but it gives me error in returning array object.
I am also trying to use _.findwhere(data, pid) which is method in module of underscore can I use it to return the object out of array?
You can use Array.prototype.find(), like this:
var data = [{
id: 1,
firstName: 'John',
lastName: 'Smith'
}, {
id: 2,
firstName: 'Jane',
lastName: 'Smith'
}, {
id: 3,
firstName: 'John',
lastName: 'Doe'
}];
data.find(x => {x.id === 1});
If you like to know more about arrays vist this link.
http://exploringjs.com/es6/ch_arrays.html
I'm not sure if you want to return the object or remove the object so I'll show you how to do both as both are very simple to do.
This is a tidied version of your data:
// this is your data
var data = [{
id: 1,
firstName: 'John',
lastName: 'Smith'
}, {
id: 2,
firstName: 'Jane',
lastName: 'Smith'
}, {
id: 3,
firstName: 'John',
lastName: 'Doe'
}];
This the loop you'll use to return the target object from the array:
// loop through the data array
for(var i = 0; i < data.length; i++) {
// check if the current item is "John Smith"
if(data[i].firstName == "John" && data[i].lastName == "Smith") {
return data[i];
}
// continue with the loop if the current item is not "John Smith"
continue;
}
This snippet does the exact same thing but without the continue:
// loop through the data array
for(var i = 0; i < data.length; i++) {
// check if the current item is "John Smith"
if(data[i].firstName == "John" && data[i].lastName == "Smith") {
return data[i];
}
}
This the loop you'll use to remove the target object from the array:
// loop through the data array
for(var i = 0; i < data.length; i++) {
// check if the current item is "John Smith"
if(data[i].firstName == "John" && data[i].lastName == "Smith") {
delete data[i];
// you can also use Array.prototype.splice() to remove an item from an array:
// data.splice(i, 1);
}
// continue with the loop if the current item is not "John Smith"
continue;
}
This snippet does the exact same thing but without the continue:
// loop through the data array
for(var i = 0; i < data.length; i++) {
// check if the current item is "John Smith"
if(data[i].firstName == "John" && data[i].lastName == "Smith") {
delete data[i];
// you can also use Array.prototype.splice() to remove an item from an array:
// data.splice(i, 1);
}
}
Use this snippet if you are using jQuery, instead of returning or deleting anything you can handle the object however you please inside the jQuery callback function.
In this case, I'll be using console.log(); as an example:
$.each(data, function(i, object) {
if(object.firstName == "John" && object.lastName == "Smith") {
console.log(object);
}
});
Good luck and all the best.
Vanilla JS:
var findWhere = function(key,val,array) {
var o;
array.some(function(object) { return object[key] == val && (o = object); });
return o;
};
var data = []; //your array
findWhere('id',1,data); //get the first object in the array where id = 1
EDIT
Here's a better one that actually takes a callback and can return just one element, or all matching elements:
var find = function(arr,cb,all) {
var o;
if(all) {
return arr.filter(cb);
}
arr.some(function(object) { return cb(object) && (o = object); });
return o;
};
var findAll = function(arr,cb) { return find(arr,cb,true); };
//return the first object in the data array where the id = 1
find(data,function(object) { return object.id == 1 });
//return all objects in the data array where name = 'John'
findAll(data,function(object) { return object.firstName = 'John'; });

get values from list of objects in javascript [duplicate]

I want to cycle through the objects contained in an array and change the properties of each one. If I do this:
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j]);
}
The console should bring up every object in the array, right? But in fact it only displays the first object. if I console log the array outside of the loop, all the objects appear so there's definitely more in there.
Anyway, here's the next problem. How do I access, for example Object1.x in the array, using the loop?
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j.x]);
}
This returns "undefined." Again the console log outside the loop tells me that the objects all have values for "x". How do I access these properties in the loop?
I was recommended elsewhere to use separate arrays for each of the properties, but I want to make sure I've exhausted this avenue first.
Thank you!
Use forEach its a built-in array function. Array.forEach():
yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});
Some use cases of looping through an array in the functional programming way in JavaScript:
1. Just loop through an array
const myArray = [{x:100}, {x:200}, {x:300}];
myArray.forEach((element, index, array) => {
console.log(element.x); // 100, 200, 300
console.log(index); // 0, 1, 2
console.log(array); // same myArray object 3 times
});
Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.
2. Check if any of the elements in an array pass a test
const people = [
{name: 'John', age: 23},
{name: 'Andrew', age: 3},
{name: 'Peter', age: 8},
{name: 'Hanna', age: 14},
{name: 'Adam', age: 37}];
const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true
3. Transform to a new array
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]
Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.
4. Sum up a particular property, and calculate its average
const myArray = [{x:100}, {x:200}, {x:300}];
const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300
const average = sum / myArray.length;
console.log(average); // 200
5. Create a new array based on the original but without modifying it
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => {
return {
...element,
x: element.x * 2
};
});
console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]
6. Count the number of each category
const people = [
{name: 'John', group: 'A'},
{name: 'Andrew', group: 'C'},
{name: 'Peter', group: 'A'},
{name: 'James', group: 'B'},
{name: 'Hanna', group: 'A'},
{name: 'Adam', group: 'B'}];
const groupInfo = people.reduce((groups, person) => {
const {A = 0, B = 0, C = 0} = groups;
if (person.group === 'A') {
return {...groups, A: A + 1};
} else if (person.group === 'B') {
return {...groups, B: B + 1};
} else {
return {...groups, C: C + 1};
}
}, {});
console.log(groupInfo); // {A: 3, C: 1, B: 2}
7. Retrieve a subset of an array based on particular criteria
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}]
Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
8. Sort an array
const people = [
{ name: "John", age: 21 },
{ name: "Peter", age: 31 },
{ name: "Andrew", age: 29 },
{ name: "Thomas", age: 25 }
];
let sortByAge = people.sort(function (p1, p2) {
return p1.age - p2.age;
});
console.log(sortByAge);
9. Find an element in an array
const people = [ {name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67} ];
const john = people.find(person => person.name === 'john');
console.log(john);
The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.
References
Array.prototype.some()
Array.prototype.forEach()
Array.prototype.map()
Array.prototype.filter()
Array.prototype.sort()
Spread syntax
Array.prototype.find()
You can use a for..of loop to loop over an array of objects.
for (let item of items) {
console.log(item); // Will display contents of the object inside the array
}
One of the best things about for..of loops is that they can iterate over more than just arrays. You can iterate over any type of iterable, including maps and objects. Make sure you use a transpiler or something like TypeScript if you need to support older browsers.
If you wanted to iterate over a map, the syntax is largely the same as the above, except it handles both the key and value.
for (const [key, value] of items) {
console.log(value);
}
I use for..of loops for pretty much every kind of iteration I do in Javascript. Furthermore, one of the coolest things is they also work with async/await as well.
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
Here's an example on how you can do it :)
var students = [{
name: "Mike",
track: "track-a",
achievements: 23,
points: 400,
},
{
name: "james",
track: "track-a",
achievements: 2,
points: 21,
},
]
students.forEach(myFunction);
function myFunction(item, index) {
for (var key in item) {
console.log(item[key])
}
}
Looping through an array of objects is a pretty fundamental functionality. This is what works for me.
var person = [];
person[0] = {
firstName: "John",
lastName: "Doe",
age: 60
};
var i, item;
for (i = 0; i < person.length; i++) {
for (item in person[i]) {
document.write(item + ": " + person[i][item] + "<br>");
}
}
It's really simple using the forEach method since ES5+. You can directly change each property of each object in your array.
myArray.forEach(function (arrayElem){
arrayElem = newPropertyValue;
});
If you want to access a specific property on each object:
myArray.forEach(function (arrayElem){
arrayElem.nameOfYourProperty = newPropertyValue;
});
myArray[j.x] is logically incorrect.
Use (myArray[j].x); instead
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
const jobs = [
{
name: "sipher",
family: "sipherplus",
job: "Devops"
},
{
name: "john",
family: "Doe",
job: "Devops"
},
{
name: "jim",
family: "smith",
job: "Devops"
}
];
const txt =
` <ul>
${jobs.map(job => `<li>${job.name} ${job.family} -> ${job.job}</li>`).join('')}
</ul>`
;
document.body.innerHTML = txt;
Be careful about the back Ticks (`)
this.data = [{name:"Rajiv", city:"Deoria"},{name:"Babbi", city:"Salempr"},{name:"Brijesh", city:"GKP"}];
for(const n of this.data) {
console.log(n.name)
}
This would work. Looping thorough array(yourArray) . Then loop through direct properties of each object (eachObj) .
yourArray.forEach( function (eachObj){
for (var key in eachObj) {
if (eachObj.hasOwnProperty(key)){
console.log(key,eachObj[key]);
}
}
});
Accepted answer uses normal function. So posting the same code with slight modification using arrow function on forEach
yourArray.forEach(arrayItem => {
var x = arrayItem.prop1 + 2;
console.log(x);
});
Also in $.each you can use arrow function like below
$.each(array, (item, index) => {
console.log(index, item);
});
Here's another way of iterating through an array of objects (you need to include jQuery library in your document for these).
$.each(array, function(element) {
// do some operations with each element...
});
Array object iteration, using jQuery,
(use the second parameter to print the string).
$.each(array, function(index, item) {
console.log(index, item);
});
var c = {
myProperty: [
{ name: 'this' },
{ name: 'can' },
{ name: 'get' },
{ name: 'crazy' }
]
};
c.myProperty.forEach(function(myProperty_element) {
var x = myProperty_element.name;
console.log('the name of the member is : ' + x);
})
This is one of the ways how I was able to achieve it.
I want to loop and deconstruction assignment at the same time, so code like this: config.map(({ text, callback })=>add_btn({ text, callback }))
This might help somebody. Maybe it's a bug in Node.
var arr = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
var c = 0;
This doesn't work:
while (arr[c].name) { c++; } // TypeError: Cannot read property 'name' of undefined
But this works...
while (arr[c]) { c++; } // Inside the loop arr[c].name works as expected.
This works too...
while ((arr[c]) && (arr[c].name)) { c++; }
BUT simply reversing the order does not work. I'm guessing there's some kind of internal optimization here that breaks Node.
while ((arr[c].name) && (arr[c])) { c++; }
Error says the array is undefined, but it's not :-/ Node v11.15.0
I know it's been long but for anyone else encountering this issue, my problem is that I was looping through an array of arrays containing only one array. Like this:
// array snippet (returned from here)
} else {
callback([results])
}
And I was using the array like this
for(const result of results){
console.log(result.x)
}
As you can see, the array I wanted to iterate over was actually inside another array. removing the square brackets helped. Node JS and MySQL.

How to loop through an array containing objects and access their properties

I want to cycle through the objects contained in an array and change the properties of each one. If I do this:
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j]);
}
The console should bring up every object in the array, right? But in fact it only displays the first object. if I console log the array outside of the loop, all the objects appear so there's definitely more in there.
Anyway, here's the next problem. How do I access, for example Object1.x in the array, using the loop?
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j.x]);
}
This returns "undefined." Again the console log outside the loop tells me that the objects all have values for "x". How do I access these properties in the loop?
I was recommended elsewhere to use separate arrays for each of the properties, but I want to make sure I've exhausted this avenue first.
Thank you!
Use forEach its a built-in array function. Array.forEach():
yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});
Some use cases of looping through an array in the functional programming way in JavaScript:
1. Just loop through an array
const myArray = [{x:100}, {x:200}, {x:300}];
myArray.forEach((element, index, array) => {
console.log(element.x); // 100, 200, 300
console.log(index); // 0, 1, 2
console.log(array); // same myArray object 3 times
});
Note: Array.prototype.forEach() is not a functional way strictly speaking, as the function it takes as the input parameter is not supposed to return a value, which thus cannot be regarded as a pure function.
2. Check if any of the elements in an array pass a test
const people = [
{name: 'John', age: 23},
{name: 'Andrew', age: 3},
{name: 'Peter', age: 8},
{name: 'Hanna', age: 14},
{name: 'Adam', age: 37}];
const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true
3. Transform to a new array
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]
Note: The map() method creates a new array with the results of calling a provided function on every element in the calling array.
4. Sum up a particular property, and calculate its average
const myArray = [{x:100}, {x:200}, {x:300}];
const sum = myArray.map(element => element.x).reduce((a, b) => a + b, 0);
console.log(sum); // 600 = 0 + 100 + 200 + 300
const average = sum / myArray.length;
console.log(average); // 200
5. Create a new array based on the original but without modifying it
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray= myArray.map(element => {
return {
...element,
x: element.x * 2
};
});
console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]
6. Count the number of each category
const people = [
{name: 'John', group: 'A'},
{name: 'Andrew', group: 'C'},
{name: 'Peter', group: 'A'},
{name: 'James', group: 'B'},
{name: 'Hanna', group: 'A'},
{name: 'Adam', group: 'B'}];
const groupInfo = people.reduce((groups, person) => {
const {A = 0, B = 0, C = 0} = groups;
if (person.group === 'A') {
return {...groups, A: A + 1};
} else if (person.group === 'B') {
return {...groups, B: B + 1};
} else {
return {...groups, C: C + 1};
}
}, {});
console.log(groupInfo); // {A: 3, C: 1, B: 2}
7. Retrieve a subset of an array based on particular criteria
const myArray = [{x:100}, {x:200}, {x:300}];
const newArray = myArray.filter(element => element.x > 250);
console.log(newArray); // [{x:300}]
Note: The filter() method creates a new array with all elements that pass the test implemented by the provided function.
8. Sort an array
const people = [
{ name: "John", age: 21 },
{ name: "Peter", age: 31 },
{ name: "Andrew", age: 29 },
{ name: "Thomas", age: 25 }
];
let sortByAge = people.sort(function (p1, p2) {
return p1.age - p2.age;
});
console.log(sortByAge);
9. Find an element in an array
const people = [ {name: "john", age:23},
{name: "john", age:43},
{name: "jim", age:101},
{name: "bob", age:67} ];
const john = people.find(person => person.name === 'john');
console.log(john);
The Array.prototype.find() method returns the value of the first element in the array that satisfies the provided testing function.
References
Array.prototype.some()
Array.prototype.forEach()
Array.prototype.map()
Array.prototype.filter()
Array.prototype.sort()
Spread syntax
Array.prototype.find()
You can use a for..of loop to loop over an array of objects.
for (let item of items) {
console.log(item); // Will display contents of the object inside the array
}
One of the best things about for..of loops is that they can iterate over more than just arrays. You can iterate over any type of iterable, including maps and objects. Make sure you use a transpiler or something like TypeScript if you need to support older browsers.
If you wanted to iterate over a map, the syntax is largely the same as the above, except it handles both the key and value.
for (const [key, value] of items) {
console.log(value);
}
I use for..of loops for pretty much every kind of iteration I do in Javascript. Furthermore, one of the coolest things is they also work with async/await as well.
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
Here's an example on how you can do it :)
var students = [{
name: "Mike",
track: "track-a",
achievements: 23,
points: 400,
},
{
name: "james",
track: "track-a",
achievements: 2,
points: 21,
},
]
students.forEach(myFunction);
function myFunction(item, index) {
for (var key in item) {
console.log(item[key])
}
}
Looping through an array of objects is a pretty fundamental functionality. This is what works for me.
var person = [];
person[0] = {
firstName: "John",
lastName: "Doe",
age: 60
};
var i, item;
for (i = 0; i < person.length; i++) {
for (item in person[i]) {
document.write(item + ": " + person[i][item] + "<br>");
}
}
It's really simple using the forEach method since ES5+. You can directly change each property of each object in your array.
myArray.forEach(function (arrayElem){
arrayElem = newPropertyValue;
});
If you want to access a specific property on each object:
myArray.forEach(function (arrayElem){
arrayElem.nameOfYourProperty = newPropertyValue;
});
myArray[j.x] is logically incorrect.
Use (myArray[j].x); instead
for (var j = 0; j < myArray.length; j++){
console.log(myArray[j].x);
}
const jobs = [
{
name: "sipher",
family: "sipherplus",
job: "Devops"
},
{
name: "john",
family: "Doe",
job: "Devops"
},
{
name: "jim",
family: "smith",
job: "Devops"
}
];
const txt =
` <ul>
${jobs.map(job => `<li>${job.name} ${job.family} -> ${job.job}</li>`).join('')}
</ul>`
;
document.body.innerHTML = txt;
Be careful about the back Ticks (`)
this.data = [{name:"Rajiv", city:"Deoria"},{name:"Babbi", city:"Salempr"},{name:"Brijesh", city:"GKP"}];
for(const n of this.data) {
console.log(n.name)
}
This would work. Looping thorough array(yourArray) . Then loop through direct properties of each object (eachObj) .
yourArray.forEach( function (eachObj){
for (var key in eachObj) {
if (eachObj.hasOwnProperty(key)){
console.log(key,eachObj[key]);
}
}
});
Accepted answer uses normal function. So posting the same code with slight modification using arrow function on forEach
yourArray.forEach(arrayItem => {
var x = arrayItem.prop1 + 2;
console.log(x);
});
Also in $.each you can use arrow function like below
$.each(array, (item, index) => {
console.log(index, item);
});
Here's another way of iterating through an array of objects (you need to include jQuery library in your document for these).
$.each(array, function(element) {
// do some operations with each element...
});
Array object iteration, using jQuery,
(use the second parameter to print the string).
$.each(array, function(index, item) {
console.log(index, item);
});
var c = {
myProperty: [
{ name: 'this' },
{ name: 'can' },
{ name: 'get' },
{ name: 'crazy' }
]
};
c.myProperty.forEach(function(myProperty_element) {
var x = myProperty_element.name;
console.log('the name of the member is : ' + x);
})
This is one of the ways how I was able to achieve it.
I want to loop and deconstruction assignment at the same time, so code like this: config.map(({ text, callback })=>add_btn({ text, callback }))
This might help somebody. Maybe it's a bug in Node.
var arr = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
var c = 0;
This doesn't work:
while (arr[c].name) { c++; } // TypeError: Cannot read property 'name' of undefined
But this works...
while (arr[c]) { c++; } // Inside the loop arr[c].name works as expected.
This works too...
while ((arr[c]) && (arr[c].name)) { c++; }
BUT simply reversing the order does not work. I'm guessing there's some kind of internal optimization here that breaks Node.
while ((arr[c].name) && (arr[c])) { c++; }
Error says the array is undefined, but it's not :-/ Node v11.15.0
I know it's been long but for anyone else encountering this issue, my problem is that I was looping through an array of arrays containing only one array. Like this:
// array snippet (returned from here)
} else {
callback([results])
}
And I was using the array like this
for(const result of results){
console.log(result.x)
}
As you can see, the array I wanted to iterate over was actually inside another array. removing the square brackets helped. Node JS and MySQL.

Categories

Resources