const obj = {
obj1: [{
name: 'Max',
age: 25
}]
}
Object.values(obj).map(obj => console.log(obj.obj1.name))
Uncaught TypeError: Cannot read property 'name' of undefined. I need to get that name
If you are just trying to loop through the object values, using forEach instead of the map is a good idea. Map returns a new array but forEach doesn't. Also, Object.values() will return an array of all the values in the object(each value is an array of objects in this case). Therefore, using 2 forEach loops makes the task easier.
const obj = {
obj1: [{
name: 'Max',
age: 25
}],
obj2: [{
name: 'Min',
age: 26
}]
}
Object.values(obj).forEach(mainObj => mainObj.forEach(obj => console.log(obj.name )))
You are trying to access the wrong key. Your object has a key obj1 which is an array. You have to loop through that array as well.
const obj = {
obj1: [{
name: 'Max',
age: 25
}],
obj2: [{
name: 'Min',
age: 24
}]
}
var objectValuesArr = Object.values(obj)
var particularObj = objectValuesArr.map(obj => obj.forEach(obj => console.log(obj.name)))
Related
I have an array with multiple objects
arr = [
{name: 'xyz',
age: 13,
},
{name: 'abc',
age: 15,
},
{name: 'abc',
age: 15,
}]
how do I find the duplicate in this array and remove the object that is duplicated in the array? They are all in one array.
Apologies. I just realized what I am trying to do is, remove the object entirely if there's a duplicate in one key... so if the age is similar, I will remove object name "def". Is this possible?
arr = [
{name: 'xyz',
entry: 1,
age: 13,
},
{name: 'abc',
entry: 2,
age: 15,
},
{name: 'def',
age: 13,
entry: 3
}]
You could achieve this by the following steps:
transform each element into an object that is key-sorted, this will make objects consistent in terms of key-value pairs order, which will help us in the next step
map the array into JSON-stringified value, and store it into a Set(), which would help us store only unique stringified objects
turn the Set() back into array
map the array back into objects by JSON.parse() each element
const arr = [
{ name: "xyz", age: 13 },
{ age: 15, name: "abc" },
{ name: "abc", age: 15 },
]
const sortKeys = obj =>
Object.fromEntries(
Object.entries(obj).sort((keyValuePairA, keyValuePairB) =>
keyValuePairA[0].localeCompare(keyValuePairB[0])
)
)
const res = Array.from(
arr
.map(sortKeys)
.map(el => JSON.stringify(el))
.reduce((set, el) => set.add(el), new Set())
).map(el => JSON.parse(el))
console.log(res)
References
Set
Object.entries()
Object.fromEntries()
I have an object:
const obj = {
name: "foo",
other: "something"
}
Creating a new object based on my object (a shallow copy) I would use the spread operator and then changing name on my new object:
const newObj = {...obj}
newObj.name = "bar";
But recently I ran into syntax that also does the trick:
const newObj = {
...obj, name: "bar"
}
How does this work and what is it called?
The two methods, you specified are equivalent. In the second method
const newObj = {
...obj, name: "bar"
}
It creates anothey key value pair with key=name and value="bar", since 1 key cannot have multiple values (if its not an array). It overtires the previous value. Code in the second method is equivalent to
const newobj = {
name: "foo",
other: "something",
name: "bar"
}
This is how spread operator works, It allows allows an iterable to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.
This explains what it does. I hope it helps.
In addition to creating shallow copies, spread allows you to merge objects. The latter will override the former. For example:
const obj = { name: 'jane', age: 22 }
const merged = { ...obj, age: 21 } // { name: 'jane', age: 21 }
const obj = { name: 'jane', age: 22 }
const merged = { ...obj, hasDog: true } // { name: 'jane', age: 22, hasDog: true }
const obj = { name: 'jane', age: 22 }
const obj2 = { age: 19, hasDog: true }
const merged = { ...obj, ...obj2 } // { name: 'jane', age: 19, hasDog: true }
MDN - Spread Syntax
I have an array in that I have objects and strings now my goal is to filter all duplicates from strings and objects.
If you don't understand, please put a comment
const data = [
'apple',
'mango',
'orange',
'grapes',
'apple',
'mango',
{
name: 'Mark',
age: 28
},
{
name: 'Mark',
age: 28
},
{
name: 'James',
age: 28
},
'sapota',
'gaua',
{
name: 'Williams',
age: 26
},
{
name: 'John',
age: 24
},
'gaua'
]
console.log(data)
One method you could use assuming you have no circular data structures
function removeDup(arr){
let known = [];
return arr.filter(elem => {
let str = JSON.stringify(elem); // Get string of whatever item we are dealing with
if(!known.includes(str)){ //Check to see if we have seen this item before
known.push(str); //If we havnt add it to seen list
return true;
}
return false;
});
}
Obviously this is constrained to anything that JSON.stringify can handle.
Also, this method assumes that in an array like:
[{name: 'name'}, 'name']
the two names are different things and will both get returned. If you want to treat them the as duplicates let me know
Note this doesn't use a forEach loop but could VERY easily be change to use one.
Is there any way to convert a list of objects into a new list where the properties are now values. I have tried to use Object.keys() and Object.values() to make two separate lists and then trying to combine them, without much success.
Example:
I want to turn:
[{ip: 123, name: "bob"}]
into:
[{property: "ip", value: 123}, {property: "name", value: "bob"}]
How do I solve this problem?
I would simply do a for loop, go through the array and then push these new objects in a new array.
The following code should solve your issue:
const array1 = [{ ip: 123, name: 'bob' }];
let newArray;
for (let i = 0; i < array1.length; i++) {
newArray.push({
property: 'ip',
value: array1[i].value
});
newArray.push({
property: 'name',
value: array1[i].name
});
}
You could use upcoming Array#flatMap and take the entries of the object.
var data = [{ ip: 123, name: "bob" }],
result = data.flatMap(o => Object.entries(o).map(([property, value]) => ({ property, value })));
console.log(result);
Traditional approach with Array#reduce.
var data = [{ ip: 123, name: "bob" }],
result = data.reduce((r, o) => [
...r,
...Object.entries(o).map(([property, value]) => ({ property, value }))
], []);
console.log(result);
I have an array as given below -
var x = [{
name: "Mr.X",
age: 22
},{
name: "Mr.Y",
age: 26
},{
name: "Mr.Z",
age: 24
},];
I want to duplicate the 2nd item and put it as the first element. Just to avoid any confusion, I want the resultant array to be as given below -
var x = [{
name: "Mr.YD",
age: 19
},{
name: "Mr.X",
age: 22
},{
name: "Mr.Y",
age: 26
},{
name: "Mr.Z",
age: 24
},];
What I have tried and got - I extracted the 2nd item, and changed the name and age properties. But it is also changing the 2nd item. I know it is because we are changing the reference. But i have no idea how to extract/duplicate item and change only its value.
if you are looking for clone of the object
there are multiple ways
jQuery Extend:
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
JSON Stringify
var newObject = JSON.parse(JSON.stringify(oldObject))
Or :
Write a clone method by iterating through object props recursively
Then append to the array using the standard array APIs
var x = [{
name: "Mr.X",
age: 22
},{
name: "Mr.Y",
age: 26
},{
name: "Mr.Z",
age: 24
},];
console.log(x);
var y = JSON.parse(JSON.stringify(x));
y.unshift({
name: "Mr.XD",
age: 19
});
console.log(y);
Unshift appends on top of array
Push appends on the end of array