Access object property values in an array of objects javascript - 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(','));

Related

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;
}

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");
}

Convert Array of Objects to Multi Dimensional Array in JavaScript

I an new to java script and have array of objects as following
[{
firstName: "John",
lastName: "Doe",
age: 46
},
{
firstName: "Mike",
lastName: "Jeffrey",
age: 56
}]
I would like to convert this array of objects to multi-dimensional array as following
[
[{
firstName: "John",
lastName: "Doe",
age: 46
}],
[{
firstName: "Mike",
lastName: "Jeffrey",
age: 56
}]
]
I am using the following code to convert to multi dimension array
var actualResult = [];
var arrayLength = inputObj.length;
for (var i = 0; i < arrayLength; i++) {
var tempResult = [];
tempResult.push(inputObj[i]);
actualResult.push(tempResult);
}
where inpuObj is my actual input.Is this the correct way of achieving the scenario?
You can use array#map. Iterate through each object and create an array.
var data = [{firstName: "John",lastName: "Doe",age: 46},{firstName: "Mike",lastName: "Jeffrey",age: 56}],
result = data.map(o => [o]);
console.log(result);

Looping through an list object

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);

Merge Array of Objects

I need to merge arrays of objects in browserside javascript like this:
[
{name: "john", age: 10},
{name: "doe", age: 14}
]
--> new data arrives
[
{name: "pete", age: 88},
{name: "larry", age: 42}
]
should become
[
{name: "john", age: 10},
{name: "doe", age: 14},
{name: "pete", age: 88},
{name: "larry", age: 42}
]
Well thats simplified the arrays will contain hundreds of larger objects. Therefore I need a performant solution.
Thanks in advance yours skeec
It seems you can just use .push() or .concat() to combine the two arrays. It does not matter what is in the arrays as the array operators just work on the elements of the array abstractly without knowing what's in them.
Here's a solution that adds the new array onto the existing one:
var data = [
{name: "john", age: 10},
{name: "doe", age: 14}
];
var newInfo = [
{name: "pete", age: 88},
{name: "larry", age: 42}
]
data = data.concat(newInfo);
Or, if you really want to keep the original array (not create a new one), you can add the new array onto the end of the original array like this:
data.push.apply(data, newInfo);
Assuming you don't need anything other than just concatenating the 2 arrays, it's supremely simple, since arrays have a method for concatenation already.
var arr1 = [
{name: "pete", age: 88},
{name: "larry", age: 42}
];
var arr2 = [
{name: "pete", age: 88},
{name: "larry", age: 42}
];
var concatArr = arr1.concat(arr2);
MDN Page on Array.prototype.concat
var arr3 = [];
for(var i in arr1){
var shared = false;
for (var j in arr2)
if (arr2[j].name == arr1[i].name) {
shared = true;
break;
}
if(!shared) arr3.push(arr1[i])
}
arr3 = arr3.concat(arr2);
You can use loadash for that:
Something like this:
var array = [1];
var other = _.concat(array, 2, [3], [[4]]);
console.log(other);
// → [1, 2, 3, [4]]
console.log(array);
// → [1]
Or for Json you can use extend like this:
lodash.extend({}, mergeInto, toMerge)

Categories

Resources