Remove an object in array from array - javascript

I want to delete the 1 ids of cardItems of my list with 0 ids and keep the order of the lists. what is the best way?
lists: [
{
id: '0',
title: 'LIST 1',
cardItems: [
{
id: '0',
text: 'Card 1',
},
{
id: '1',
text: 'Card 2',
},
{
id: '2',
text: 'Card 3',
},
],
},
]

You can use .find to get the list item by id, and then remove the card item using .filter:
const lists = [
{
id: '0',
title: 'LIST 1',
cardItems: [
{ id: '0', text: 'Card 1' },
{ id: '1', text: 'Card 2' },
{ id: '2', text: 'Card 3' },
],
},
];
const removeCardItem = (list, listItemId, cardItemId) => {
const arr = [...list];
// get list item by id
const item = arr.find(listItem => listItem.id === listItemId);
// remove card item by id if found
if(item)
item.cardItems = item.cardItems.filter(cardItem =>
cardItem.id !== cardItemId
);
return arr;
}
console.log( removeCardItem(lists, '0', '1') );

Something similar to
if(lists[0].cardItems[0].id === 1){
lists[0].cardItems.splice(0,1);
}
Obviously this will only check that one value, but this can easily be implemented into a loop or nested loops or whatever you need. (I can't know since I can't see all of your code)
Your question is a little bit hard to understand, but this was my best guess at helping you out! If this wasn't the answer you're looking for then please give us more information so we can help you more effectively!

Related

Walk through a nested array using index in JavaScript

I want walk through a nested array and need to find the target element in the array. An example path [2, 1] should return {text: 'More 2'} and path [2, 2, 1] should return { text: 'Other-2' }. I tried lodash functions but no luck yet.
My Nested array is given below:
var data = [
{ text: 'Item 1', },
{ text: 'Item 2', },
{
text: 'More',
children: [
{ text: 'More 1', children: [] },
{ text: 'More 2'},
{ text: 'Other', children:[ {text: 'Other-1'}, {text: 'Other-2'}, {text: 'Other-3'} ] }
]
}
];
Well, it's not a multi-dimensional array, nor is it a raggedy array-of-arrays. It's an array of objects (that happen contain other arrays of objects that happen to...).
Lodash's _.get() ought to do the trick for you:
const _ = require('lodash');
const data = data = [
{ text: 'Item 1', },
{ text: 'Item 2', },
{
text: 'More',
children: [
{ text: 'More 1', children: [] },
{ text: 'More 2'},
{ text: 'Other', children:[ {text: 'Other-1'}, {text: 'Other-2'}, {text: 'Other-3'} ] }
]
}
];
const widget = _.get(obj, '[2].children[1]');
console.log('widget',widget);
Or... roll your own. It's not that hard to walk the tree:
function select(data, ...path) {
let i = path.shift() ;
let node = data[i] ;
while ( node && (i=path.shift()) !== undefined ) {
node = node?.children?.[i] ;
}
return node ;
}
const widget = select( data, 2, 1 );
console.log(widget);

Javascript filter method, Remove all Items with matching values in array

I'm trying to remove all items if they match with array values but it's removing only one item. How can i remove all items with filter method or what is the best way to achieve this.
let data = [
{
id: '1',
title: 'ABC'
},
{
id: '2',
title: 'DEF'
},
{
id: '3',
title: 'GHI'
},
{
id: '4',
title: 'JKL'
},
{
id: '5',
title: 'MNO'
}
]
data = data.filter(post => {
let remove = ['2', '4', '5']
for(let i = 0; i < remove.length; i++) {
return post.id !== remove[i]
}
})
console.log(data)
Thanks
you should return false if you want to remove item from array
let data = [
{
id: '1',
title: 'ABC'
},
{
id: '2',
title: 'DEF'
},
{
id: '3',
title: 'GHI'
},
{
id: '4',
title: 'JKL'
},
{
id: '5',
title: 'MNO'
}
]
let remove = ['2', '4', '5']
data = data.filter(post => {
return !remove.includes(post.id);
})
console.log(data)
All the notice are in the snippet's comment
let data = [ { id: '1', title: 'ABC' }, { id: '2', title: 'DEF' }, { id: '3', title: 'GHI' }, { id: '4', title: 'JKL' }, { id: '5', title: 'MNO' } ]
const remove = ['2', '4', '5']
// `indexOf` is from ES5
data = data.filter(post => remove.indexOf(post.id) === -1)
console.log(data)
// `includes` is from ES7
data = data.filter(post => !remove.includes(post.id))
console.log(data)
// this will recreate the array ['2', '4', '5'] 5 times
data = data.filter(post => !['2', '4', '5'].includes(post.id))
console.log(data)
There is no need to use for loop inside of filter.
Instead it is possible to use some method inside of filter. The some method checks whether at least one element satisfies condition inside of provided function. So unnecessary iteration will be avoided:
data.filter(f => !remove.some(s => s == f.id))
An example:
let data = [
{
id: '1',
title: 'ABC'
},
{
id: '2',
title: 'DEF'
},
{
id: '3',
title: 'GHI'
},
{
id: '4',
title: 'JKL'
},
{
id: '5',
title: 'MNO'
}
]
let remove = ['2', '4', '5']
console.log(data.filter(f => !remove.some(s => s == f.id)));
I'll suggest using includes rather then a nested for loop.
You should also move the remove var outside of the loop, so it's not reinitialised every time.
The callback to the filter method is a predicate. If the condition evaluates to true, the current value in the iteration will be returned. In your case, you want to return if the current value is not in the remove array.
let data = [
{
id: '1',
title: 'ABC'
},
{
id: '2',
title: 'DEF'
},
{
id: '3',
title: 'GHI'
},
{
id: '4',
title: 'JKL'
},
{
id: '5',
title: 'MNO'
}
]
const remove = ['2', '4', '5']
data = data.filter(post => {
return !remove.includes(post.id)
})
console.log(data)

Postman - How to add items into array and then using array elements randomly?

I have this json
This JSON represents a shopping cart
I need to get all "id" parameters into an array and set that array as environment variable. There can be multiple "id" parameters in JSON. Then I need to use elements from created array randomly. (I need to remove items from cart randomly based on id)
Is there a way to achieve that? I'm struggling to find a solution for that.
Thank you
First get the whole reponse, parse it. You have put that code in Tests tab of postman
For your case:
var array = JSON.parse(responseBody).order.commerceItems;
var ids = [];
for(var i=0; i< array.length; i++)
{
ids.push(array[i].id);
}
Now put the ids in environment variable or global variable of PostMan.
postman.setEnvironmentVariable("ProductIds",JSON.stringify(ids));
After this, it will look like this.
Now when you want to access a id from that ids randomly, you have to write in Pre-request Script tab, like this:
and in request body:
let order = {
commerceItems:[
{
name: 'test1',
id: 1
},
{
name: 'test2',
id: 2
},
{
name: 'test3',
id: 3
}
]
};
let arr = [];
for (item of order.commerceItems) {
arr.push(item.id);
}
console.log(arr);
[1, 2, 3]
if you only want to return random data from your array of object, you can doing like this :
let order = {
id: "7824t70ujhfiu",
totalCommerce: 5,
commerceItems:[
{
value: 'value 1',
anotheValue: 'another one 1',
name: 'name 1',
id: "iuhvue0743bg3y"
},
{
value: 'value 2',
anotheValue: 'another one 2',
name: 'name 2',
id: "sdhvuhsdupvhh9y470y3yg"
},
{
value: 'value 3',
anotheValue: 'another one 3',
name: 'name 3',
id: "o0402t207t782yt78"
},
{
value: 'value 4',
anotheValue: 'another one 4',
name: 'name 4',
id: "72b07t347y74y7by"
},
{
value: 'value 5',
anotheValue: 'another one 5',
name: 'name 5',
id: "oin98y49yb2y49y"
}
]
};
pickRandom = () => {
var arr = order.commerceItems;
return arr[Math.floor(Math.random() *arr.length)];
}
const random_data = [pickRandom(), pickRandom()];
const filter_array = [...new Map(random_data.map(item => [item.id, item])).values()];
order = {
...order,
totalCommerce: filter_array.length,
commerceItems: filter_array
};
console.log(order);

How to filter nested data in computed data (VueJS)?

The idea is pretty simple.
In a computed variable, I want to filter sections using needle, but instead of just displaying matched sections and attached questions (like in my example below), I want to exclude questions where title doesn't match AND section title doesn't match.
Here is the initial set of datas :
const sections =
[
{
title: 'Title section 1',
questions : [
{
title: 'Title question 1'
},
{
title: 'Title question 2'
}
]
},
{
title: 'Title section 2',
questions : [
{
title: 'Title question 3'
},
{
title: 'Title question 4'
}
]
}
]
Here is the expected results :
When needle is "section 1" :
const filteredArray = [
{
title: 'Title section 1',
questions : [
{
title: 'Title question 1'
},
{
title: 'Title question 2'
}
]
}
]
When needle is "question 1" :
const filteredArray = [
{
title: 'Title section 1',
questions : [
{
title: 'Title question 1'
}
]
}
]
And so on.
Here is the code I've written :
const sections =
[
{
title: 'Title section 1',
questions : [
{
title: 'Title question 1'
},
{
title: 'Title question 2'
}
]
},
{
title: 'Title section 2',
questions : [
{
title: 'Title question 3'
},
{
title: 'Title question 4'
}
]
}
]
const needle = 'question 4'
const filteredArray = sections.filter(section => section.title.toLowerCase().indexOf(needle.toLowerCase()) !== -1 ||
section.questions.filter(question => question.title.toLowerCase().indexOf(needle.toLowerCase()) !== -1).length > 0)
console.log(filteredArray)
As you can see, filtered results are good, but I'm not able to exclude questions when question title AND section title doesn't match.
An idea ?
NB : I'm using vuejs 2, so my original array is comming from the store, and to keep reactivity, I can't use an other array.
I would use Array.prototype.reduce to achieve such a result:
const needleTitle = 'section 2'
const needleQuestion = 'question 4'
const filteredArray = sections.reduce((acc, section) => {
// filtering 1-level section list by pushing to acc only needed items
if (section.title.toLowerCase().indexOf(needleTitle.toLowerCase()) >= 0) {
// filtering 2-level question list by replacing section.questions with a new list
const questions = section.questions.filter(question =>
question.title.toLowerCase().indexOf(needleQuestion.toLowerCase()) >= 0
)
acc.push({ ...section, questions });
}
return acc;
}, []);
Also, you see, I splitted needle to needleTitle and needleQuestion. Probably it is not exactly what you want, but the idea should be useful. The code above will result
[
{
title: 'Title section 2',
questions : [
{
title: 'Title question 4'
}
]
}
]
Thanks to #dhilt, here is the final solution :)
const sections =
[
{
title: 'Title section 1',
questions : [
{
title: 'Title question 1'
},
{
title: 'Title question 2'
}
]
},
{
title: 'Title section 2',
questions : [
{
title: 'Title question 3'
},
{
title: 'Title question 4'
}
]
}
]
const needle = 'question 4'
const filteredArray = sections.reduce((acc, section) => {
// Pushing entire section if we find needle in section title
if (section.title.toLowerCase().indexOf(needle.toLowerCase()) >= 0) {
acc.push({ ...section })
} else {
// Pushing section with filtered questions when question title match
const questions = section.questions.filter(question =>
question.title.toLowerCase().indexOf(needle.toLowerCase()) >= 0
)
if (questions.length > 0) {
acc.push({ ...section, questions })
}
}
return acc
}, [])
console.log(filteredArray)

How to find item in array of objects

I have array like this :
array = [
{
id:'ABC',
content: ''XYZ,
people :
[
'User 1',
'User 2'
]
}
{
id:'ABC',
content: ''XYZ,
people :
[
'User 3',
'User 4'
]
}
]
I want to find obj have people = user 3. Here my code bellow :
array.forEach(function(item, index){
var item = item.reverse().find(item => item.people.indexOf('User 3'));
console.log(item);
});
Because I want get latest obj so I use reverse(). It's not working ? What can I do now. Thank
Try this;
array.forEach(function(item){
if(item.people.indexOf('User 3') > -1);
console.log(item);
});
Here's how you can filter such objects -
let array = [{
id: 'ABC',
content: '',
people: [
'User 1',
'User 2'
]
}, {
id: 'ABC',
content: '',
people: [
'User 3',
'User 4'
]
}];
console.log(array.filter(obj => -1 != obj.people.indexOf("User 3")));
You aren't using the item or index argument to the forEach function (you name some other things item, but you never use the arguments), so your function is going to do the same thing every iteration.
var result = array.find( function ( item ) {
return item.people.includes( 'User 3' );
})
result will be 1 object. If you're looking for all objects with User 3, use filter instead of find.
This will give you most recent result.
const arr = [
{
id:'ABC',
content: 'XYZ',
people :
[
'User 1',
'User 2'
]
},
{
id:'ABC',
'content': 'XYZ',
'people' :
[
'User 3',
'User 4'
]
}
]
console.log(arr.filter(item => item.people.includes('User 3')).slice(-1)[0]);
One option is to use filter() to get all result of the search. Use pop() to get the last one.
let array = [
{"id":"ABC","content":"XYZ","people":["User 1","User 2"]},
{"id":"ABC","content":"XYZ","people":["User 3","User 4"]},
{"id":"XXX","content":"XXX","people":["User 3","User 4"]}
];
let toSearch = 'User 3';
let result = array.filter(o => o.people.includes(toSearch)).pop();
console.log(result);
You can also use Array.find() method like:
var array = [
{
id:'ABC',
content: 'XYZ',
people :
[
'User 1',
'User 2'
]
},
{
id:'ABC',
content: 'XYZ',
people :
[
'User 3',
'User 4'
]
}
];
var res = array.find(obj => obj.people.indexOf('User 3') !== -1);
console.log(res);

Categories