With Javascript how can I get the id of each object in this kind of object:
array = [
{ active: false, defaultTag:true, id: '507f191e810c19729de860ea', title: 'one' },
{ active: false, defaultTag:true, id: '507f191e810c19722de860ea', title: 'two' }
];
I need to fetch the id in order to check if the item already exists in the array whe a use intent to save the same object again.
Best regards
Americo
here you can get array of unique ids
var unique = [],
tmp, i = 0;
while(i < array.length){
unique.indexOf(tmp = array[i++].id) > -1 ? array.pop(i--) : unique.push(tmp)
}
console.log(unique);
Gather all your items under one object using Array.reduce. This will filter out duplicates
Use Object.values to get the values inside your object. The returned value is the filtered array
const array = [
{ active: false, defaultTag:true, id: '507f191e810c19729de860ea', title: 'duplicateOne' },
{ active: false, defaultTag:true, id: '507f191e810c19729de860ea', title: 'one' },
{ active: false, defaultTag:true, id: '507f191e810c19722de860ea', title: 'two' }
];
const removeDupsById = arr => Object.values(
arr.reduce((a, c) => ({...a, [c.id]: c}), {})
);
console.log(removeDupsById(array));
Related
I have a list array:
list: [
{
id: '3',
title: 'hi',
},
{
id: '4',
title: 'there',
},
],
I'm using a method to do some destructuring and return and new array while looking for an item by id
return {
title: section.title,
list: [
...section.list,
storeSections[i].list.filter((field) => field.id === ownId)[0],
],
};
If it finds it, it will just add it to the new array, for example this object:
{
id: '3515',
title: 'hello',
},
But if it doesn't, it will add 'undefined' to the new array, because the filter method will return undefined.
Is there a simple way to change this behavior so that the filter method only adds an item to the array if it finds it?
use spread, when the array is empty you will not get the extra entry.
var a = [1,2,3];
var b = [4];
var c = [];
console.log([...a, ...b, ...c])
so
return {
title: section.title,
list: [
...section.list,
...storeSections[i].list.filter((field) => field.id === ownId),
],
};
One solution I found is to add:
list: [
...section.list,
storeSections[i].list.filter((field) => field.id === ownId)[0],
].filter((item) => item !== undefined),
Anothef filter method to remove the undefined values
I'm trying to iterate over an array of objects that looks like this:
const arr = [{
id: 1,
name: "John",
storeName: "Amazon",
price: 100,
isRecieved: false,
deliveryDate: some date
}, ....]
I'm iterating over the array with product ID that I received from the user, finding the relevant item according to it's id and changing the key "isRecieved" from false to true.
This is my code:
const filterReceivedProduct = (list, id) => {
const changeReceivedState = list.filter((item) => {
return item.id === id ? **item[isRecieved]** = true : item;
})
return changeReceivedState
}
But when I'm trying to access the object using bracket notation it return the value (in this case 'false') and I can't change the value to true..
What I'm doing wrong?
You don't need to use .filter() here. The filter method is for removing elements from an array. What you want to do is map each element/object to a new object, which has all the properties from the old object, containing an updated isRecieved property. To create a new object with all the properties of the old object, you can spread the properties and values from the old object into a new one ({...item}). You can then update the isRecived based on your whether the item id matched the id passed into your function:
const arr = [{
id: 1,
name: "John",
storeName: "Amazon",
price: 100,
isRecieved: false,
deliveryDate: 'some date'
}, {
id: 2,
name: "Alex",
storeName: "Apple",
price: 200,
isRecieved: false,
deliveryDate: 'some date2'
}];
const filterReceivedProduct = (list, id) =>
list.map(item => ({
...item,
isRecieved: item.id === id // sets isRecieved to true or false based on the equalty comparison
}));
const res = filterReceivedProduct(arr, 1);
console.log(res);
By creating a new object within the .map() callback, you're never mutating the original objects in your arr, treating everything as immutable.
Here filter make no sense. Filter use to filter some array based on condition. If you just want to change some property of an object inside array then use map for this purpose.
See below example.
const arr = [{
id: 1,
name: "John",
storeName: "Amazon",
price: 100,
isRecieved: false,
deliveryDate: 'some date'
}, {
id: 2,
name: "Doe",
storeName: "Amazon",
price: 100,
isRecieved: false,
deliveryDate: 'some date'
}];
filterReceivedProduct = (list, id) => {
return list.map(item => {
if(item.id === id) {
item.isRecieved = true;
}
return item;
});
}
console.log(filterReceivedProduct(arr, 1))
i want to access the id 'qwsa221' without using array index but am only able to reach and output all of the array elements not a specific element.
i have tried using filter but couldnt figure out how to use it properly.
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Use Object.keys() to get all the keys of the object and check the values in the array elements using . notation
let lists = {
def453ed: [{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Object.keys(lists).forEach(function(e) {
lists[e].forEach(function(x) {
if (x.id == 'qwsa221')
console.log(x)
})
})
You can use Object.Keys method to iterate through all of the keys present.
You can also use filter, if there are multiple existence of id qwsa221
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
let l = Object.keys(lists)
.map(d => lists[d]
.find(el => el.id === "qwsa221"))
console.log(l)
you can do it like this, using find
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
console.log(
lists.def453ed // first get the array
.find( // find return the first entry where the callback returns true
el => el.id === "qwsa221"
)
)
here's a corrected version of your filter :
let lists = {def453ed: [{id: "qwsa221",name: "Mind"},{id: "jwkh245",name: "Space"}]};
// what you've done
const badResult = lists.def453ed.filter(id => id === "qwsa221");
/*
here id is the whole object
{
id: "qwsa221",
name: "Mind"
}
*/
console.log(badResult)
// the correct way
const goodResult = lists.def453ed.filter(el => el.id === "qwsa221");
console.log(goodResult)
// filter returns an array so you need to actually get the first entry
console.log(goodResult[0])
I have a plain JavaScript array of objects, say e.g.
const drawings = [
{
name: "Foo",
category: "widget"
},
{
name: "Bar",
category: "widget"
},
{
name: "Bar",
category: "fidget"
},
]
etc, where both the name and category have duplicates. What I want to end up with is essentially a list of objects (this is to meet the interface for a 3rd party library), where each object represents a name, and then for each category there is a property that is either true or false, depending on the original list. So for the example the output would be:
const output = [
{
name: "Foo",
widget: true,
fidget: false
},
{
{
name: "Bar",
widget: true,
fidget: true
},
]
I would first go through and make an object of your categories with the categories as keys and default values as false.
Then you can assign this to each object and set the correct keys to true as you go through.
const drawings = [{name: "Foo",category: "widget"},{name: "Bar",category: "widget"},{name: "Bar",category: "fidget"},]
// make category object where everything is false
let category_obj = drawings.reduce((a, item) => (a[item.category] = false, a), {})
let output = drawings.reduce((a, {name, category}) => {
// assign cat
if (!a.hasOwnProperty(name)) a[name] = Object.assign({}, {name}, category_obj)
// set to true if the correct category
a[name][category] = true
return a
}, {})
// the above makes an object, but you only want the array of values
console.log(Object.values(output))
If you already know the categories or if you have infered them as you suggested, you could use Array.reduce() like such:
drawings.reduce(function(acc, curr) {
if (!acc.some(elt => elt.name === curr.name)) {
acc.push({name: curr.name, widget: false, fidget: false})
}
const i = acc.findIndex(elt => elt.name === curr.name)
acc[i][curr.category] = true
return acc
}, [])
Is there a way in ES6, to set value of a key in all objects, in an array of objects to a new value.
[
{title: 'my title', published: false},
{title: 'news', published: true},
...
]
For example, setting every item published value to true?
The array in your example is just a one-dimensional array of objects.
You can do what you asked with forEach and a lambda:
array.forEach(element => element.published = true);
I'd use a loop.
arr represents your array of objects
var result = []
for (var i = 0; i < arr.length; i++) {
result.push([arr[i].title, arr[i].published])
}
console.log(result)
this will result in [['my Title', false], ['news', true]]
Use map
arr = arr.map( s => (s.published = true, s) );
Edit
No need to set the return value either, just
arr.map( s => (s.published = true, s) );
would suffice
Demo
var arr = [{
title: 'my title',
published: false
},
{
title: 'news',
published: true
}
];
arr.map(s => (s.published = true, s));
console.log(arr);
If you don't want a loop you can refer with index.
a = [
{title: 'my title', published: false},
{title: 'news', published: true}
]
a[0].published= true;
a[1].published= true;
or loop it
for (val in a) {
a[val].published = true;
}
You can use the map function with spread operator
let array = [
{ title: 'my title', published: false },
{ title: 'news', published: true }
]
array = array.map(t => t.published !== true ? { ...t, published: true } : t)