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);
Related
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);
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!
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);
What I want is to push all objects from arrayToPush into array but only the ones that has different id. So in this case I would like to have an array with id's 111,222,333,444,555 and do not push object in arrayToPush that has id 333. How can i achieve that? Thanks in advance
var array = [
{title: 'Something', id: 111},
{title: 'Something 2', id: 222},
{title: 'Something 3', id: 333}
]
var arrayToPush = [
{title: 'Something 4', id: 333},
{title: 'Something 5', id: 444},
{title: 'Something 6', id: 555}
]
for(var i = 0; i < arrayToPush.length; i++) {
array.push(arrayToPush[i])
}
One way to do it is to filter the ArrayToPush to eliminate the existing elements and then contact both of them using the spread operator :
var array = [
{ title: "Something", id: 111 },
{ title: "Something 2", id: 222 },
{ title: "Something 3", id: 333 }
];
var arrayToPush = [
{ title: "Something 4", id: 333 },
{ title: "Something 5", id: 444 },
{ title: "Something 6", id: 555 }
];
var filtered = arrayToPush.filter(a => !array.find(b => b.id === a.id));
var result = [...array, ...filtered];
console.log(result);
You could loop over arrayToPush and check if the object exists on array with array.find()
arrayToPush.forEach(x => {
if (!array.find(e => e.id === x.id)) {
array.push(x)
}
})
First you need to know which ids you have in the array:
const arrayIds = array.map(({ id }) => id); // [111, 222, 333]
Then you need to filter the arrayToPush, so you loop through the arrayToPush and filter those that are not included the the array:
const filteredArrayToPush = arrayToPush.filter(({ id }) => !arrayIds.includes(id));
And then concat both arrays array and filteredArrayToPush:
array = [...array, ...filteredArrayToPush];
I've got multiple items, some of them with the same title. I want to create an multidimensional array with the title as the first key and a unique number as the second key. So it's possible to categorize the items by title.
Example:
itemArray['title1'][0] = item1
itemArray['title1'][1] = item2
itemArray['title2'][0] = item3
My example is working with this code, but in my opinion it's to complicated and I hope there is an other way with JavaScript.
let itemArray = {}
items.forEach(item => {
let title = item['title']
if (itemArray[title] == null) {
itemArray[title] = {}
}
let index = Object.keys(itemArray[title]).length
itemArray[title][index] = item
},
)
The Input:
[ RowDataPacket {
uid: 1,
title: 'booktitle',
description: 'description' },
RowDataPacket {
uid: 2,
title: 'booktitle',
description: 'description 2' },
RowDataPacket {
uid: 1,
title: 'booktitle 2',
description: 'description' } ]
Expected output (Since it's the result of a sql query the item is a RowDataPacket):
{ 'booktitle':
{ '0':
RowDataPacket {
uid: 1,
title: 'booktitle',
description: 'description' } },
{ '1':
RowDataPacket {
uid: 2,
title: 'booktitle',
description: 'description 2' } },
'booktitle 2':
{ '0':
RowDataPacket {
uid: 1,
title: 'booktitle 2',
description: 'description' } }
}
It's easy with PHP, there it's working like this:
$itemArray = array();
foreach ($items as $key => $item) {
$itemArray[$item['title']][] = $item;
}
Thanks in advance!
You could reduce the array by taking a default array and push the item.
var items = [{ title: 'title1' }, { title: 'title1' }, { title: 'title2' }],
result = items.reduce((r, item) => {
(r[item.title] = r[item.title] || []).push(item);
return r;
}, {});
console.log(result);
You've got the correct idea. The itemArray you created is not a multidimensional array. It's an object with each title as key and an array of items which share the same title as their value. You could probably simplify your forEach like this:
var items = [{
uid: 1,
title: 'booktitle',
description: 'description'
}, {
uid: 2,
title: 'booktitle',
description: 'description 2'
}, {
uid: 1,
title: 'booktitle 2',
description: 'description'
}]
let itemArray = {}
items.forEach(item => {
itemArray[item.title] = itemArray[item.title] || [];
itemArray[item.title].push(item)
})
console.log(itemArray)
Checck if itemArray already has the title as a key. If yes, use it. Else, point it to an empty array []. Then just push the current item to that property.
With reduce, you can even simplify it to:
var items=[{uid:1,title:'booktitle',description:'description'},{uid:2,title:'booktitle',description:'description 2'},{uid:1,title:'booktitle 2',description:'description'}]
let itemArray = items.reduce((acc,i) =>
((acc[i.title] = acc[i.title] || []).push(i), acc)
,{})
console.log(itemArray)
Expected output
{ 'booktitle':
{ '0':
RowDataPacket {
uid: 1,
title: 'booktitle',
description: 'description' } },
{ '1':
RowDataPacket {
uid: 2,
title: 'booktitle',
description: 'description 2' } },
'booktitle 2':
{ '0':
RowDataPacket {
uid: 1,
title: 'booktitle 2',
description: 'description' } }
}
That's a bad practice. Don't use enumerated properties on Objects. You see how cumbersome they are. Unlike PHP, JS has no associative Arrays; so using Objects for that is the right equivalent. But for indexed Arrays you should use Arrays in JS, not Objects.
var data = [{
uid: 1,
title: 'booktitle',
description: 'description'
},
{
uid: 2,
title: 'booktitle',
description: 'description 2'
},
{
uid: 1,
title: 'booktitle 2',
description: 'description'
}
];
const booksByTitle = {};
for (const item of data) {
const {
title
} = item;
if (!(title in booksByTitle)) booksByTitle[title] = [];
booksByTitle[title].push(item);
}
console.log(booksByTitle);
.as-console-wrapper{top:0;max-height:100%!important}
but there are also plenty of frameworks in JS that offer some groupBy method, something like this quick implementation:
var data = [{
uid: 1,
title: 'booktitle',
description: 'description'
},
{
uid: 2,
title: 'booktitle',
description: 'description 2'
},
{
uid: 1,
title: 'booktitle 2',
description: 'description'
}
];
function groupBy(iterable, keyOrFn) {
const fn = typeof keyOrFn === "function" ?
keyOrFn :
(item) => item == null ? undefined : item[keyOrFn];
var result = Object.create(null);
for (const item of iterable) {
const key = fn(item);
if (key in result) {
result[key].push(item);
} else {
result[key] = [item];
}
}
return result;
}
const booksByTitle = groupBy(data, "title");
console.log(booksByTitle);
.as-console-wrapper{top:0;max-height:100%!important}