javascript finding a key in nested object [duplicate] - javascript

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
How to find object in array by property in javascript?
(3 answers)
Closed 4 months ago.
I have an object called _test shaped in the below form where the first element is id and the second is name:
"_test": [
{id:1, name:andy},{id:2, name:james}, {id:3, name:mike}
]
I then have another field called key. the values that key takes on can equal values of id in the subs
key
I currently use
_test.flatMap( c => c.id).find(elem => elem == key) || null
How can I get this to return the name? I'm at a loss and having a major brain fart.

You can find the name for a given id via:
const
_test = [
{ id: 1, name: 'Andy' },
{ id: 2, name: 'James' },
{ id: 3, name: 'Mike' }
],
key = 2,
{ name } = _test.find(({ id }) => id === key) ?? {};
console.log(name); // James

actually is pretty easy, you just need to use find on your array, it takes a function as an argument.
pd: when doing ([id, name]) I'm destructuring the array, you can change that to:
names.find(entry => key === entry[0])
const names = [
[1, 'andy'],
[2, 'james'],
[3, 'mike']
];
const key = 3;
const solution = names.find(([id, name]) => key === id)
console.log("solution => ", solution)
console.log("just the name => ",
solution[1]);

Related

Adding key value to inner array in a multidimensional array when key doesn't exist (javascript) [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 months ago.
I need to develop a function whereby a type property gets appended to an array if it doesn't exist.
So the key will be of type and it should have a value of "dog".
Can someone kindly point out how I can iterate over the array to check if the key "type" exists and also provide guidance on how to append {type:"dog"} to the inner array if it doesn't exist. I tried animalArray[0][1]={type:"dog"} but it doesnt seem to work.
A typical array of animals will look like this:
labelTheDogs(
[
{name: 'Obi'},
{name: 'Felix', type: 'cat'}
]
)
// should return [
{name: 'Obi', type: 'dog'},
{name: 'Felix', type: 'cat'}
]
This is not a nested array
function labelTheDogs(dogs) {
dogs.forEach(dog => {
if (!dog.type) {
dog.type = 'dog'
}
})
return dogs
}
const dogs = labelTheDogs(
[{
name: 'Obi'
},
{
name: 'Felix',
type: 'cat'
}
]
)
console.log(dogs)
you can use the map function to do that
const newArray = yourArray.map((element) => {
if(!element.type){
element.type = "dog";
}else {
return element
}
})

Get value from object in array: js [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 2 years ago.
This is what my array looks like:
const items = [
{ uuid: '123-1234-567', amountMoney: '20,02' },
{ uuid: '111-111-111', amountMoney: '44.04' }
]
And I have the uuid key in the variable:
const uuid = '111-111-111';
Now based on this uuid, I would like to extract the value from the amountMoney: 44.04.
How do you write this in a nice way in js?
You can use Array.prototype.find:
items.find(item => item.uuid === uuid) // -> found object
Use Array.prototype.find to find the object if the property uuid of the object matches the value of the variable uuid. Before extracting the value for amountMoney check if the object was found.
Example,
const items = [
{ uuid: '123-1234-567', amountMoney: '20,02' },
{ uuid: '111-111-111', amountMoney: '44.04' }
]
const uuid = '111-111-111';
const foundItem = items.find(item => item.uuid === uuid);
if (foundItem) {
console.log(foundItem.amountMoney)
}

Map an array of Javascript objects to sorted unique array by a specific attribute [duplicate]

This question already has answers here:
Converting string array to Name/Value object in javascript
(4 answers)
Closed 4 years ago.
How do I convert a string array:
var names = [
"Bob",
"Michael",
"Lanny"
];
into an object like this?
var names = [
{name:"Bob"},
{name:"Michael"},
{name:"Lanny"}
];
Super simple Array.prototype.map() job
names.map(name => ({ name }))
That is... map each entry (name) to an object with key "name" and value name.
var names = [
"Bob",
"Michael",
"Lanny"
];
console.info(names.map(name => ({ name })))
Silly me, I forgot the most important part
names.map(name => name === 'Bob' ? 'Saab' : name)
.map(name => ({ name }))
Use the Array.map() function to map the array to objects. The map() function will iterate through the array and return a new array holding the result of executing the function on each element in the original array. Eg:
names = names.map(function(ele){return {"name":ele}});
You can do this too:
var names = [
"Bob",
"Michael",
"Lanny"
];
var objNames = []
names.forEach(name => {
objNames.push({
name
})
})
Using ES6 you can set name and it is equal to name: name
you can use the map function.
In general, list.map(f) will produce a new list where each element at position i is the result of applying f to the element at the same position in the original list.
For example:
names.map(function(s) {
return {name: s}
});

remove duplicates from array inside array of objects [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 3 years ago.
This doesn't work
const uniqueArray = this.allusers.user_ids.filter((thing,index) => {
return index === this.allusers.user_ids.findIndex(obj => {
return JSON.stringify(obj) === JSON.stringify(thing);
});
});
this.allusers.user_ids = uniqueArray
This is the example of my json
0:{
code: "sdsdll"
id: 10
type: "New User"
unit: "Amount"
updated_at: "2019-08-20 09:01:24"
user_ids: (2) [2, 2, 3, 4, 3]
value: "12.00"
__proto__: Object
}
1: {code: "ssddl", id: 9, code: "sklsdsd",...........…}
2: {code: "sdds", id: 11, code: "dsfsdf232",...........…}
I want to remove the duplicates from user_ids array inside array of objects.
Try (something like this)*:
Immutable way:
this.allusers = this.allusers.map(userObj => {
return Object.assign({}, userObj, {
user_ids: Array.from(new Set(userObj.user_ids))
})
});
(*) iterating the object array and mapping each object to a new object with the duplicate user_ids removed by the new Set(...) and in the form of an Array by the Array.from(...)
Mutating original objects: (as #Kaddath mentioned in the comments this keeps other possible existing references to the user objects as it mutates them instead of replacing)
this.allusers.forEach(userObj => {
userObj.user_ids = Array.from(new Set(userObj.user_ids))
});
You can use a set to dedupe an array. All you then need to do is convert it back to an array: [...new Set(user_ids)]
const data = [{"code":"sdsdll","id":10,"type":"New User","unit":"Amount","updated_at":"2019-08-20 09:01:24","user_ids":[2,2,3,4,3],"value":"12.00"},{"code":"sdsdll2","id":101,"type":"New User 2","unit":"Amount","updated_at":"2019-08-20 09:01:24","user_ids":[4,11,2,2,3,4,4,3],"value":"12.00"}];
const out = data.map(({ user_ids, ...rest }) => {
const dedupedIds = [...new Set(user_ids)];
return { user_ids: dedupedIds, ...rest };
});
console.log(out);
Look like your allusers is an array so you can not call .user_ids on it. You can loop through it and process user_ids field of each element with Set.
let allusers = [{code: "sdsdll",id: 10,type: "New User",unit: "Amount",updated_at: "2019-08-20 09:01:24",user_ids: [2, 2, 3, 4, 3],value: "12.00"},{code: "sdsdll2",id: 101,type: "New User 2",unit: "Amount",updated_at: "2019-08-20 09:01:24",user_ids: [4, 2, 2, 3, 4, 4, 5],value: "12.00"}];
allusers.forEach((user) => user.user_ids = [...new Set(user.user_ids)]);
console.log(allusers);
If you want to delete the duplicate values, you can do as follows:
var user_ids = Array.from(new Set(user_ids));

Javascript string array to object [duplicate]

This question already has answers here:
Converting string array to Name/Value object in javascript
(4 answers)
Closed 4 years ago.
How do I convert a string array:
var names = [
"Bob",
"Michael",
"Lanny"
];
into an object like this?
var names = [
{name:"Bob"},
{name:"Michael"},
{name:"Lanny"}
];
Super simple Array.prototype.map() job
names.map(name => ({ name }))
That is... map each entry (name) to an object with key "name" and value name.
var names = [
"Bob",
"Michael",
"Lanny"
];
console.info(names.map(name => ({ name })))
Silly me, I forgot the most important part
names.map(name => name === 'Bob' ? 'Saab' : name)
.map(name => ({ name }))
Use the Array.map() function to map the array to objects. The map() function will iterate through the array and return a new array holding the result of executing the function on each element in the original array. Eg:
names = names.map(function(ele){return {"name":ele}});
You can do this too:
var names = [
"Bob",
"Michael",
"Lanny"
];
var objNames = []
names.forEach(name => {
objNames.push({
name
})
})
Using ES6 you can set name and it is equal to name: name
you can use the map function.
In general, list.map(f) will produce a new list where each element at position i is the result of applying f to the element at the same position in the original list.
For example:
names.map(function(s) {
return {name: s}
});

Categories

Resources