Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have data like:
var data = [
{
items: [
{
id: 123
},
{
id: 234
},
{
id: 123
}
]
}, {
items: [
{
id: 123
},
{
id: 234
}
]
}
]
so, I want count object deep in array inside of all data by property 'id'.
ex: data.countObject('id',123) //return 3.
and my data have about xx.000 item, which solution best?
Thanks for help (sorry for my English)
You can use reduce & forEach. Inside the reduce callback you can access the items array using curr.items where acc & curr are just parameters of the call back function. Then you can use curr.items.forEach to get each object inside items array
var data = [{
items: [{
id: 123
},
{
id: 234
},
{
id: 123
}
]
}, {
items: [{
id: 123
},
{
id: 234
}
]
}];
function getCount(id) {
return data.reduce(function(acc, curr) {
// iterate through item array and check if the id is same as
// required id. If same then add 1 to the accumulator
curr.items.forEach(function(item) {
item.id === id ? acc += 1 : acc += 0;
})
return acc;
}, 0) // 0 is the accumulator, initial value is 0
}
console.log(getCount(123))
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I have an array of objects and I would like to replace an object with a new object that has a specific id. My goal is to replace/remove the object where id === 'hotel' with an entirely new object and keep the same index.
Example / Current Code
const sampleArray = [{ id: 'price' }, { id: 'hotel1', filters: [] }, { id: 'type' }]
const index = sampleArray.findIndex((obj) => obj.id === 'hotel1') // find index
sampleArray = sampleArray.splice(index, 0) // remove object at this index
sampleArray.splice(index, 0, { id: 'hotel2' }) // attempt to replace with new object ... not working :(
You don't need the fancy splice logic. Just set the array element and forget it.
const sampleArray = [{ id: 'price' }, { id: 'hotel1', filters: [] }, { id: 'type' }]
const index = sampleArray.findIndex((obj) => obj.id === 'hotel1'); // find index
sampleArray[index] = { id: 'hotel2' }; // replace with new object ... working :)
console.log(JSON.stringify(sampleArray));
You can use the map() function:
const updatedArray = sampleArray.map(item => item.id === 'hotel' ? {...item, id: 'hotel2'} : item);
Another way, replacing an array element by index
const sampleArray = [{ id: 'price' }, { id: 'hotel1', filters: [] }, { id: 'type' }]
const index = sampleArray.findIndex((obj) => obj.id === 'hotel1'); // find index
Object.assign(sampleArray, { [index]: { id: 'hotel2' } }); // replace with new object
console.log(sampleArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Group javascript array items on value
Assuming you have a json object like:
[
{
prNumber: 20000401,
text: 'foo'
},
{
prNumber: 20000402,
text: 'bar'
},
{
prNumber: 20000401,
text: 'foobar'
},
]
Is it possible to perform a "join" on prNumber?
For example, maybe the desired output would be something like:
[
{
prNumber: 20000401,
text: [
'foo',
'foobar'
]
},
{
prNumber: 20000402,
text: [
'bar'
]
}
]
I have no code samples worth anything, so I will not post them here.
This would preferrably use vanilla javascript, but will accept a jQuery answer.
You should iterate the initial array and create new objects keyed off the prNumber. Here's how to do it using reduce (assuming you've assigned the array to a variable named orig):
var result = orig.reduce(function(prev, curr, index, arr) {
var num = curr["prNumber"];
if (!prev[num]) {
prev[num] = [];
}
prev[num].push(curr["text"]);
return prev;
}, {});
You can easily convert this into the example structure outlined in your question.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
Improve this question
In my project, I have to work with a list of complex objects, even nested ones.
For this question, I will replace that with a basic object: {value: number}
I have an array of that object, and now I would like to go over the array and check the object's value:
// First way: Using one function:
console.log("Way #1")
// So I have an array like this:
itemArr = [{
value: 1
}, {
value: 2
}, {
value: 3
}, {
value: 1
}]
// The function is implemented outside of the objects:
const check = (item) => {
switch (item.value) {
case 1:
return "is one"
case 2:
return "is two"
case 3:
return "is three"
}
}
itemArr.forEach((item) => {
console.log(check(item))
})
// Second way
// The function is implemented inside of the object.
console.log("Way #2")
itemArr = [{
value: 1,
check: () => "is one"
}, {
value: 2,
check: () => "is two"
}, {
value: 3,
check: () => "is three"
}, {
value: 1,
check: () => "is one" // this way, even if a value is repeated, I have to write the function again.
}]
itemArr.forEach((item) => {
console.log(item.check())
})
Is there an obviously better choice in general?
Which way is more efficient / has better performance?
The first way is better. The Second way creates a function in memory for every object of the array.
Reference for better memory management
But in the real time try to find some generic way so that the things can be done in a loop.
none of them.
it seems absurd to me because it derogates from the maintainability rules of the code: the informational data must not be mixed in the algorithmic part
do that ?
const itemArr =
[ { value: 1 }
, { value: 2 }
, { value: 3 }
, { value: 1 }
]
const check = []
check[3] = 'is three'
check[1] = 'is one'
check[2] = 'is two'
// or : const check = [,'is one','is two','is three' ]
itemArr.forEach(({value: x}) => console.log(check[x]))
if you absolutely want to use a function...
const itemArr =
[ { value: 1 }
, { value: 2 }
, { value: 3 }
, { value: 1 }
]
const checkItem = (()=>
{
const msg = []
msg[3] = 'is three' // in any order you want
msg[1] = 'is one'
msg[2] = 'is two'
return (val) => msg[val]
})()
itemArr.forEach(({value: x}) => console.log(checkItem(x)))
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a Object in this format.
const obj = [{
name: 'name',
items: [{
name: 'name 1',
items: [
{ value: 100 },
{ value: 50 }
]
}]
}]
Imagine that all arrays repeat several times in length and an object inside another.
How I can iterate all objects in all arrays and check if all have the property "name" and "items", if it doesn't have check if has the property "value".
I trying to make a recursion but I don't no how to check if the last "items" has a value to stop and continue to check the rest.
Thanks everyone.
You can use Object.prototype.hasOwnProperty to check if an object has a specific property and Array.prototype.flatMap to map the inner arrays to a single array.
const obj = [{
name: 'name',
items: [{
name: 'name 1',
items: [
{ value: 100 },
{ value: 50 },
{
name: 'name 2',
items: [{
value: 150
}]
}
]
}]
}];
function getValues(arr) {
return arr.flatMap(entry => {
if (entry.hasOwnProperty('name') && entry.hasOwnProperty('items')) {
return getValues(entry.items);
}
return entry.value;
});
}
console.log(getValues(obj));
I resolve my question with:
function check(objs) {
for (let obj of objs) {
if(!('name' in obj) &&
!('value' in obj))
throw new Error('invalid')
if('name' in obj)
check(obj.items)
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a SortableList where you can organize your order to make filter priorities.
like that:
[
0: "Fruits",
1: "Legumes",
2: "Example1",
]
then I have some data like this:
[
{
id: 0,
_source: {
someOtherProps,
source: "Fruits"
}
},
{
id: 1,
_source: {
someOtherProps,
source: "Example1"
}
},
.... blablabla
]
I want to sort the data by the source, respecting the order priorities.
I try to use the sort() function, but I don't have any ideas how I could do that.
In this example: I will have all my data object sorted firstly by the source "Fruits", then "Legumes" then "Example1".
You could use an object for the sort order and take the delta as result for the callback.
var order = { Fruits: 1, Legumes: 2, Example1: 3 },
data = [{ id: 0, _source: { source: "Fruits" } }, { id: 1, _source: { source: "Example1" } }];
data.sort((a, b) => order[a._source.source] - order[b._source.source]);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }