I'm creating an empty array and fill it with object.
export const model = [
{isMine: false},
]
const newArr = Array(25);
newArr.fill(model);
newArr.forEach((item) => {
console.log(item);
})
This logs out all objects with the array. But I don't know how to log out the isMine property... I always get undefined
I hope this is what you need. If you spread (...) the model it will get stored as objects. But if you don't spread it will be stored as an array inside an array which contain an object
const model = [
{isMine: false},
]
const newArr = Array(25).fill(...model);
newArr.forEach((item) => {
console.log(item.isMine);
})
I hope this helps, you need to access array inside array
const model = [
{isMine: false},
];
console.log(model[0].isMine);
const newArr = Array(25);
newArr.fill(model);
console.log(newArr);
newArr.forEach(x => x.forEach(y => console.log(y.isMine)));
newArr is a 2 dimensional array, since model is an array.
So to access the property isMine in your forEach loop you'd do:
newArr.forEach((item) => {
// item is an array, so get the value at the first index
console.log(item[0].isMine);
})
Related
I have a problem to filters data inside the array of objects by an array of objects. I already try using filters combine with the includes method but returning an empty array.
let's say I have array an array called listOfPermissions.
listOfPermissions = [
{name:'A',IsChecked:true},
{name:'B',IsChecked:true},
{name:'C',IsChecked:true}
]
Than i want to filter the list with permissionOnRole array
permissionOnRole = [
{name:'C',IsChecked: true}
]
The goals i want to achieve
result = [
{name:'A',IsChecked:true},
{name:'B',IsChecked:true},
]
this is my code
const setUncheckPermissions = () => {
const permissionsOnRole = role.permissions.map(it => ({name: it, isChecked: true}))
const listOfAllPermissions = props.permissions.map((permission) => {return {name: permission['name'], isChecked: true}});
let result = listOfAllPermissions.filter(item => permissionsOnRole.includes(item));
console.log(listOfAllPermissions)
}
please help me to solve this problems
Thank you in advance
Just use filter
const listOfPermissions = [
{name:'A',IsChecked:true},
{name:'B',IsChecked:true},
{name:'C',IsChecked:true}
]
const permissionOnRole = [
{name:'C',IsChecked: true}
]
const result = listOfPermissions.filter(item => !!permissionOnRole.find(i => i.name !== item.name))
console.log(result)
Hello I'm trying to create an object that includes under the same property name a bunch of array values,
This what I'm trying
const quiz = [
{question: 'Who is the main character of DBZ',
options: ['Vegetta','Gohan','Goku']}
]
const newObj = {
options: []
}
quiz.forEach((item)=>{
item.options.forEach((item, index)=>{
newObj.options[`name${index}`] = item
})
})
expected value =
newObj = {
options: [{name: 'Vegetta'},{name:'Gohan'},{name:'Goku'}]
}
actual value received =
newObj = {
{ options: [ name0: 'Vegetta', name1: 'Gohan', name2: 'Goku' ] }}
Thanks in advance!
As you've noticed, newObj.options[`name${index}`] = item creates a new key on your options array, and sets that to item. You instead want to push an object of the form {name: item} into your array. There are a few ways you could go about this, one way is to use .push() like so:
quiz.forEach((item)=>{
item.options.forEach((item)=>{
newObj.options.push({name: item});
})
});
while not as common, you can also use set the current index of options, which is slightly different to the above example, as it will maintain the same index, which can be important if quiz is a sparse array that you want to keep the same indexing of on options:
quiz.forEach((item)=>{
item.options.forEach((item, index)=>{
newObj.options[index] = {name: item};
})
});
Example of the difference:
const arr = [1, 2,,,5]; // sparse array
const pushRes = [];
const indxRes = [];
arr.forEach(n => pushRes.push(n));
arr.forEach((n, i) => indxRes[i] = n);
console.log("Push result", pushRes);
console.log("Index result", indxRes);
For a different approach, you also have the option of using something like .flatMap() and .map() to create your options array, which you can use to create newObj:
const quiz = [
{question: 'Who is the main character of DBZ',
options: ['Vegetta','Gohan','Goku']}
];
const options = quiz.flatMap(({options}) => options.map(name => ({name})));
const newObj = {options};
console.log(newObj);
I had a lists of duplicate array of String and array of object. I want to find the property into one particular object of array uniquely without duplication of array object.
If can done in lodash library, it would be awesome.
const arr1 = ['test#email', 'test2#email']
const arr2 = [{ id: 1, email: 'test#email' }]
Expected result
['test2#email']
this is what I done so far
By turning arr1 into object frist so I can compare with arr2
const emailLists = _.map(arr, function (item) {
console.log(item)
return { email: item }
})
then merge them to together and used uniq to remove duplicates
const merge = _.unionBy(array1, array2, 'email')
const result _.uniq(merge, 'email');
I think it still not a good process and not clean
You can do it without lodash
const arr1 = ['test#email', 'test2#email']
const arr2 = [{ id: 1, email: 'test#email' }]
const emailToDelete = arr2.map(a => a.email)
const result = arr1.filter(e => !emailToDelete.includes(e))
console.log(result)
You can use lodash chain to solve that:
const result = _([...arr1, ...arr2.map(i => i.email)]) // ['test#email', 'test2#email', 'test#email']
.countBy() // { test#email: 2, test2#email: 1 }
.pickBy(count => count === 1) // { test2#email: 1 }
.keys() // ['test2#email']
.value();
You can use filter on the first array and check that an email address matches with some of your objects in the second array. So even if it matches with multiple objects, the matching email will only be in the output once.
I want to find the property into one particular object of array uniquely without duplication of array object
So then your expected output is wrong, as you provide an email that is not found in the object array. I guess that was a typo in your question.
const arr1 = ['test#email', 'test2#email']
const arr2 = [{ id: 1, email: 'test#email' }]
const result = arr1.filter(search => arr2.some(({email}) => email == search));
console.log(result);
Hello so i have array of objects something like this
const old = [{id: 1, name: 'Random'}, {id: 2, name: 'Random2'}]
also i have array
const wantedField = ['id']
So looking this result, i need values only for certain key
const finally = [[1],[2]]
I have tried something like this but not luck. End result should be array of arrays with just certain values.
old.map((obj, value) => {
const key = Object.keys(obj)[value]
if(wantedField.includes(const)) {
const newArray = []
const key = Object.keys(obj)[value]
newArray.push(obj[key])
return [newArray]
}
})
So this return [newArray] is wrong should return multiple values not just one. Please help regards.
This is a one-liner, with two nested maps. One to iterate over the input array, and another to iterate over the wanted field(s):
const old = [{id: 1, name: 'Random'}, {id: 2, name: 'Random2'}];
const wantedField = ['id'];
const result = old.map(o => wantedField.map(k => o[k]));
console.log(result);
I have this two states:
stateOne: [
'marca01',
'marca02'
]
stateTwo: [
{
PRODUCTO:'hat',
PRICE:1499,
CATEGORY:'Men'
},
{
PRODUCTO:'Shirt',
PRICE:1233,
CATEGORY:'Woman'
}
]
And I'm using lodash to merge both in a third state, but as you see the first state is an array and the second one is an array of objects so I can't merge these two like I want to...
Something like this:
stateThree: [
{
PRODUCTO:'hat',
PRICE:1499,
CATEGORY:'Men',
MARK:'marca01'
},
{
PRODUCTO:'Shirt',
PRICE:1233,
CATEGORY:'Woman',
MARK:'marca02'
}
]
How can I get the desired result (is not necessary to use lodash)
Without lodash :
const state3 = state2.map((product, index) => ({
...product,
MARK: state1[index]
}));
Here .map returns a new array whose new values are returned by the anonymous function.
The spread operator ...product flattens the previous object properties in the new object. This syntaxic sugar can be replaced by Object.assign.
Then we add a new MARK property based on the other state with the same index.
I used the map method and the spread operator in order to prevent state mutation which can be harmful in React.
You could iterate over the second array, and add the properties.
let s1 = [
'marca01',
'marca02'
]
let s2 = [
{
PRODUCTO:'hat',
PRICE:1499,
CATEGORY:'Men'
},
{
PRODUCTO:'Shirt',
PRICE:1233,
CATEGORY:'Woman'
}]
s2.forEach((x,i) => x.MARK = s1[i])
console.log(s2)
You can do like this:
stateThree = stateTwo.map( (element, i) => ({...element, MARK: stateOne[i] } ))