Looping through an list object - javascript

I need to get a specific object out of a list by using a for loop
For example i would have this:
var list = [
{Name: "Jake", Age: 15},
{Name: "Paul", Age: 20}
];
Very simple right here but what i need to do is return the variable Name from each object, so that i should only get in this case Jake and Paul and not the age information. I know i can use a simple list[0].Name to give me an output but its more so in a case of a extreme amount of names that i would like to use a for-loop to loop through and return every name.

What you're looking for is map:
const newList = list.map(function(element){
return element.Name;
});
The map function iterates over an array and returns a new value for each iterated value.
In this case, the above function will return a new array with strings representing only the Name property of each object in the list.
For the same function, only with arrow notation and destructuring, please review:
const newList = list.map(({Name}) => Name);

Here's a simple for-loop:
var list = [{Name: "Jake", Age: 15}, {Name: "Paul", Age: 20}]
let names = [];
for (let i = 0; i < list.length; i++) {
names.push(list[i].Name);
}
console.log(names);
Here's the same result with forEach:
var list = [{Name: "Jake", Age: 15}, {Name: "Paul", Age: 20}]
let names = [];
list.forEach(function (obj) {
names.push(obj.Name);
});
console.log(names);
Adding to Gilad's answer using map if you wanted to you could create a general function that will return the values of a specified object property so that you don't need to repeat code.
var list = [{Name: "Jake", Age: 15}, {Name: "Paul", Age: 20}]
function getValue(key) {
return function (obj) {
return obj[key];
}
}
let names = list.map(getValue('Name'));
let ages = list.map(getValue('Age'));
console.log(names, ages);

Related

How can I convert an array of objects into an array of objects with the same values but with modified keys?

I have an array with objects and want to convert this to an array containing the same values but with different key names. (JavaScript)
For example, an array of
[{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}]
becomes
[{identification: "Bob", years: 50, person: true}, {identification: "Jerry", years: 20, person: true}]
Using the Map function works perfectly here.
const people = [
{name: "Bob", age: 50, person: true},
{name: "Jerry", age: 20, person: true}
];
const formatted = people.map((person) => ({
identification: person.name,
years: person.age,
person: person.person
});
This should work for this problem.
I think that you may use the map method this method returns and array with the same length as the one you are mapping:
const array = [{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}];
let newKeysArray = array.map( a => {
let obj = {
identification: person.name,
years: person.age,
person: person.person
};
return obj
} );
So inside the map you are assigning the values that you need to a new object and return the object as the mapped item.
Just in case you prefer to modify the objects in place, you can make use of a strategy by nverba here:
let rows = [
{name: "Bob", age: 50, person: true},
{name: "Jerry", age: 20, person: true}
];
let keyMaps = [
['name', 'identification'],
['age', 'years'],
];
for(let keyMap of keyMaps)
for(let row of rows)
delete Object.assign(row, {[keyMap[1]]: row[keyMap[0]] })[keyMap[0]];
console.log(rows);
keyMap[1] is the new key. keyMap[0] is the old key. Object.assign takes the value of the old key and places it in the new key. The delete keyword is confusing, but it doesn't apply to row as a whole. It's only deleting the old key.

How can I filter an array of objects with a value from another object?

I want to write a function which takes an array of objects with certain key value pairs as the first argument. And an object with key value pairs as the second argument.
The function should check if the key value pairs from the second argument are found in the array of objects from the first argument.
If so, it should return an array of objects which have the matching name and value pairs.
For example, if I have an array of objects (first argument):
[{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
And as the second argument:
{age: 17}
It should return:
[{name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
Because of the matching value age
This is what I have come up with but don't know what to put in the for...in loop:
function checkTheName(list, check) {
let newArr = [];
for(let i = 0; i < list.length; i++){
for(let key in list[i]){
// Stuck here
}
}
return newArr;
}
You can do this with filter and every methods.
let a = [{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
let b = {age: 17}
function checkTheName(list, check) {
return list.filter(o => Object.keys(check).every(k => {
return (k in o) && check[k] == o[k]
}))
}
console.log(checkTheName(a, b))
A simple ES6 version with Array.prototype.filter and Array.prototype.every:
const data = [{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}];
const fObj = {age: 17};
const filtred = data.filter(item =>
Object.keys(fObj).every(k => item.hasOwnProperty(k) && item[k] === fObj[k])
);
console.log(filtred);
You can loop over the array and test for that property:
function checkTheName(check, list){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}
var array =[{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon",
age: 17}, {namenter code heree: "Poopy", age: 17}]
;
var resultObject = checkTheName( array,"string 1");
Use filter to loop over the array.
function findByAge(myArr, obj){
myArr.filter( (item) => {
if(obj.age === item.age){
return item
}
})
}
This will return an array with just the array items that you are looking for.
You can call it following line. Since the function returns a new array. We need to give the new array a name (newArray in this example).
var newArray = findByAge(myArr, obj)
You need to put an if condition comparing the age value of your check object with the age value of the list object. In case, both the values are equal, push object in newArr.
let list = [{ name: "Peter", age: 21 }, { name: "Kate", age: 18 }, { name: "Tihon", age: 17 }, { name: "Poopy", age: 17 }],
check = { age: 17 };
function checkTheName(list, check) {
let newArr = [];
for (let i = 0; i < list.length; i++) {
if (list[i].age == check.age) {
newArr.push(list[i]);
}
}
return newArr;
}
console.log(checkTheName(list, check));
Alternatively, you can also use array#filter.
let list = [{name: "Peter", age: 21}, {name: "Kate", age: 18}, {name: "Tihon", age: 17}, {name: "Poopy", age: 17}],
check = {age: 17},
result = list.filter(o => o.age === check.age);
console.log(result);
var filterobj ={age:17};
var data=[{name: "Tihon", age: 17}, {name: "Poopy", age: 17}]
var newArray = data.filter(function (el) {
return el.age ==filterobj.age;
}

Can we add properties to immutable object in JavaScript?

An object is like:
const obj = [{name: 'Alex', age: 20}, {name: 'James', age: 22}];
This obect is immutable from Immutable.js.
Is it possible to add a new key for each object? example:
const obj = [{name: 'Alex', age: 20, city: 'New York'}, {name: 'James', age: 20, city: 'Rome'}];
Not if it’s immutable. But that is ok, you can copy all the properties over to a new structure and add whatever you need to that way:
const newData = obj.map(person => ({
...person,
city: someLogicToDetermineCity(person)
}))
function someLogicToDetermineCity(person) {
// logic based on person
return city
}
const doesn't create immutability - it just means that the reference assigned to it on creation cannot be changed later (which simply means that you cannot assign a new value to it).
See these examples:
const a = {}
a = { name: "peter" } // => TypeError: invalid assignment to const `a'
However it's no problem to assign a property on a:
const a = {}
a.name = "peter"
console.log(a); // => { "name": "peter" }
The same applies for Array objects:
const arr = [{}]
arr.push(1);
arr[0].name="peter"
console.log(arr);
// [
// {
// "name": "peter"
// },
// 1
// ]

Check if same object exists in an array - Javascript

I have an array of objects as follows
[{name: "jack", age: 10}, {name: "john", age: 15}]
Consider that i have an object
{name: "jack", age: 10}
Now i need to check if this object exist in the array. If all the properties(name, age) of the object matches, then display an alert on the page.
How to accomplish this using pure javascript?
Use Array.some, Array.every and Object.entries
A match will be counted if
There are equal number of keys
There is a match for every key/value pair
var arr = [{name: "jack", age: 10}, {name: "john", age: 15}];
var input = {name: "jack", age: 10};
var result = arr.some((o) => Object.entries(input).every(([k,v]) => o[k] === v) && Object.keys(input).length === Object.keys(o).length);
console.log(result);
Try this:
var data = [{name: "jack", age: 10}, {name: "john", age: 15}];
var input = {name: "jack", age: 10};
for(var i=0;i<data.length;i++)
{
if(data[i].name==input.name && data[i].age == input.age)
{
alert('matched');
break;
}
}
This may be a bad performing method, but it would cover nested object cases with ease. Also this is only suited if ALL key/value pairs must match and that the key/value pairs were defined in the same order.
let c = [{name: "jack", age: 10}, {name: "john", age: 15}],
s = {name: "jack", age: 10};
console.log(c.filter(e => JSON.stringify(s) === JSON.stringify(e)));
You can try this if you don't want to check for index of object inside array object
var obj = [{name: "jack", age: 10}, {name: "john", age: 15}];
var checkObj = {name: "john", age: 15};
if(JSON.stringify(obj).indexOf(JSON.stringify(checkObj)) >= 0){
console.log("Object Available");
}else{
console.log("Object Not Available");
}

Access object property values in an array of objects javascript

I have an array containing objects that looks like this:
var persArr = [
{name: "Adam", age: 37},
{name: "Ben", age: 36},
{name: "Chris", age: 46}
];
What I would like to do is create a string variable which takes the given names in each object in the array and puts them together like this:
var str = "Adam, Ben, Chris";
Any suggestions as to achieve this?
You can use map and join:
var str = persArr.map(function (pers) {
return pers.name;
}).join(", ");
Try with:
var names = [];
for (var k in persArr) {
names.push(persArr[k].name);
}
var str = names.join(', ');
try something like this
var persArr = [{name: "Adam", age: 37}, {name: "Ben", age: 36}, {name: "Chris", age: 46}];
var ar_length = persArr.length;
var temp_arr = [];
for(var i= 0;i<ar_length;i++){
temp_arr.push(persArr[i].name);
}
alert(temp_arr.join(','));

Categories

Resources