map objects in multidimensional array javascript react native based on column index - javascript

I have a two history objects that are podcasts and articles, i want to display both in the same screen in descending order by which time they were clicked,
Here are the variables of original article and podcast from DB
var { articles, articlesInHistory, podcastsInHistory, podcasts } = this.props.stores.appStore;
Here is my article Object from history: console.log("dataItem", articlesInHistory)
dataItem Array [
Object {
"currentTime": 1585439646,
"id": "156701",
Symbol(mobx administration): ObservableObjectAdministration {
"defaultEnhancer": [Function deepEnhancer],
"keysAtom": Atom {
"diffValue": 0,
"isBeingObserved": true,
"isPendingUnobservation": false,
"lastAccessedBy": 26,
"lowestObserverState": 2,
"name": "appStore#1.articlesInHistory[..].keys",
"observers": Set {},
},
"name": "appStore#1.articlesInHistory[..]",
"pendingKeys": Map {
Symbol(Symbol.toStringTag) => false,
"hasOwnProperty" => false,
"toJSON" => false,
},
"proxy": [Circular],
"target": Object {
"currentTime": 1585439646,
"id": "156701",
Symbol(mobx administration): [Circular],
},
"values": Map {
"id" => "156701",
"currentTime" => 1585439646,
},
},
},
,]
And podcast from history: console.log("dataItem", podcastsInHistory)
dataItem Array [
Object {
"currentTime": 1585439636,
"id": "4",
Symbol(mobx administration): ObservableObjectAdministration {
"defaultEnhancer": [Function deepEnhancer],
"keysAtom": Atom {
"diffValue": 0,
"isBeingObserved": true,
"isPendingUnobservation": false,
"lastAccessedBy": 26,
"lowestObserverState": 2,
"name": "appStore#1.podcastsInHistory[..].keys",
"observers": Set {},
},
"name": "appStore#1.podcastsInHistory[..]",
"pendingKeys": Map {
Symbol(Symbol.toStringTag) => false,
"hasOwnProperty" => false,
"toJSON" => false,
},
"proxy": [Circular],
"target": Object {
"currentTime": 1585439636,
"id": "4",
Symbol(mobx administration): [Circular],
},
"values": Map {
"id" => "4",
"currentTime" => 1585439636,
},
},
},
]
now i want to order the two components using currentTime in condition
for example if this podcast was first then i should return
<PodcastList navigate={navigate} podcast={podcast} key={index} />)
Or if the article is first then show
<SmallArticle key={index} article={article} />
i need them mixed not like articles on top and podcast bottom, i been searching arrays sort but couldn't solve it.
I want a condition based on currentTime and using an id to identify or match objects thanks.

As you don´t know from the data if its an article or a podcast (there is no attribute in your objects that tells you that), you can´t put them in the same list-array.
The only way to know if you should render an Article or a Podcast component is based on what list you are reading.
Keep two indexes, articleIndex = 0 and podcastIndex = 0 (you can keep that in your state), and read the actual article and podcast for respective list, and compare the current time. Then you will know what component to render, and advance the corresponding list index.
In pseudo code:
while articleIndex < articlesList.length && podcastIndex < podcastList.length do:
if articlesList[articleIndex].currentTime < podcastList[pocastIndex].currentTime do:
render <SmallArticle article={articlesList[articleIndex]} key ={articleIndex}/>//render SmallArticle
articleIndex += 1; //advance index
else do:
render <PodcastList podcast={podcastList[postcastIndex]} key={podcastIndex} />
podcastIndex +=1;
when the while statement finishes, is because one of the list has been fully traversed. You need to traverse the rest of the other and render the respect component.
If you show me some of your components code can help you with code in more detail, but I don´t know the context.

Related

Destructuring object with inner array without all keys

I have an object like this:
const objBefore:
{
"id": "3pa99f64-5717-4562-b3fc-2c963f66afa1",
"number": "5000",
"enabled": true,
"classes": [
{
"id": "2fc87f64-5417-4562-b3fc-2c963f66afa4",
"name": "General"
},
{
"id": "7ffcada8-0215-4fb0-bea9-2266836d3b18",
"name": "Special"
},
{
"id": "6ee973f7-c77b-4738-b275-9a7299b9b82b",
"name": "Limited"
}
]
}
Using es6, I want to grab everything in the object except the name key of the inner classes array to pass it to an api.
So:
{
"id": "3pa99f64-5717-4562-b3fc-2c963f66afa1",
"number": "5000",
"enabled": true,
"classes": [
{"id": "2fc87f64-5417-4562-b3fc-2c963f66afa4"},
{"id": "7ffcada8-0215-4fb0-bea9-2266836d3b18"},
{"id": "6ee973f7-c77b-4738-b275-9a7299b9b82b"}
]
}
The closest I got was: let {id, number, enabled, classes: [{id}]} = objBefore;
But it only gets me one id in classes. I've tried spreading above using [...{id}] or [{...id}]. Same thing.
I find it challenging to get the right mental model for how to think about this when it's on multiple levels. In my mind, when I say [...{id}] I'm thinking, "I want the id property as an object in the outer classes array, but give me every id in the array!"
Clearly I'm not thinking about this correctly.
I've tried it using map to get that part but I'm still having trouble combining it back to the original to produce the desired result. for example:
let classIds = objBefore.classes.map(({id}) => {
return {
id
}
})
(Using the map syntax, how can I destructure in the function the other keys that are one level higher?)
To combine them I started trying anything and everything, :
let {id, number, enabled, classIds} = {objBefore, [...classIds]} // returns undefined for all
I'd prefer to do it in one statement. But if that's not possible, then what's a clean way to do it using map?.
You can't destructure and map at the same time in the way you're looking to do it. The main purpose of destructuring assignment is to extract data from an array/object and not for manipulating data. In your case, as you're after an object with the same keys/value as your original object, just with a different classes array, I would instead suggest creating a new object and spreading ... the original object into that. Then you can overwrite the classes array with a mapped version of that array:
const objBefore = { "id": "3pa99f64-5717-4562-b3fc-2c963f66afa1", "number": "5000", "enabled": true, "classes": [ { "id": "2fc87f64-5417-4562-b3fc-2c963f66afa4", "name": "General" }, { "id": "7ffcada8-0215-4fb0-bea9-2266836d3b18", "name": "Special" }, { "id": "6ee973f7-c77b-4738-b275-9a7299b9b82b", "name": "Limited" } ] };
const newObj = {
...objBefore,
classes: objBefore.classes.map(({id}) => ({id}))
};
console.log(newObj);
How about using simple util method with object destructuring, spread operator and map
const objBefore = {
id: "3pa99f64-5717-4562-b3fc-2c963f66afa1",
number: "5000",
enabled: true,
classes: [
{
id: "2fc87f64-5417-4562-b3fc-2c963f66afa4",
name: "General",
},
{
id: "7ffcada8-0215-4fb0-bea9-2266836d3b18",
name: "Special",
},
{
id: "6ee973f7-c77b-4738-b275-9a7299b9b82b",
name: "Limited",
},
],
};
const process = ({ classes, ...rest }) => ({
...rest,
classes: classes.map(({ id }) => ({ id })),
});
console.log(process(objBefore))
In one line, you could do this:
const objAfter = { ...objBefore, classes: objBefore.classes.map(item => ({ id: item.id })) };
Or, if you prefer:
const objAfter = {...objBefore, classes: objBefore.classes.map(({id}) => ({id}))};
There isn't any way in object destructing to copy an entire array of objects into a different array of objects by removing properties so you use .map() for that.

Compare all object elements of two different arrays

sorry for my English at the start.
I have a problem with filtering a list of products posted in JSON. The code is written in react native with the use of react redux.
The object of each product looks like this:
ProductTest {
"barcode": "barcode",
"brand": "brand",
"category": "category",
"description": "description",
"details": "details",
"filters": Object {
"cienkie": false,
"farbowane": false,
"krecone_i_puszczace": false,
"normalne": false,
"oslabione": false,
"przetluszczajace": false,
"suche_i_zniszczone": false,
"wszystkie": true,
},
"id": "0",
"image": "image",
"ingredients": "ingredients",
"name": "name",
},
And the "appliedFilters" list looks like this:
Object {
"cienkie": false,
"farbowane": false,
"krecone_i_puszczace": false,
"normalne": false,
"oslabione": false,
"przetluszczajace": false,
"suche_i_zniszczone": false,
"wszystkie": false,
}
I don't know how to make the "appliedFilters" list to be compared with the "filters" for each product, and to return the matching products from the list.
If you have any ideas I would be greatful.
You can use the array filter method :
let keys = Object.keys(appliedFilters);
let filteredList = productList.filter(product => {
let matching = true;
keys.forEach(key => {
if(product.hasOwnProperty(key)){
if(!(product.filters[key] === appliedFilters[key])) matching = false;
}
}
if(matching) return product;
})
If you are sure that the attributes order of the filter and the product objects will not change, you can simplify like this :
let filteredList = productList.filter(product => JSON.stringify(product.filters) === JSON.stringify(appliedFilters))

Taking contents of an array of objects, and assigning them to a property on a JSON object

I want to take items from this array (the way I save things on the client)
[
{
"id": "-Mdawqllf_-BaW63gMMM",
"text": "Finish the backend[1]",
"status": true,
"time": 1625248047800
},
{
"id": "-Mdawqllf_-BaW63gGHf",
"text": "Finish the middle-end[2]",
"status": false,
"time": 1625248040000
},
{
"id": "-Mdawqllf_-BaW63gGHd",
"text": "Finish the front-end[3]",
"status": false,
"time": 1625248040000
}
]
And turn them into this format for how I save it server side
{ "todos": {
"-Mdawqllf_-BaW63gMMM": {
"text": "Finish the backend[1]",
"status": true,
"time": 1625248047800,
},
"-Mdawqllf_-BaW63gGHf": {
"text": "Finish the middle-end[2]",
"status": false,
"time": 1625248040000,
},
"-Mdawqllf_-BaW63gGHd": {
"text": "Finish the front-end[3]",
"status": false,
"time": 1625248040000,
}
},
}
Basically i turn items into an array on the client to help with sorting and making use of arrays. But before sending it back need to put into the right format
Use .map() to loop over the array of objects to exctract the id property, so you can use it as the key of the new object.
Use Object.fromEntries() to create the new object from the array returned by .map().
const data = [
{
"id": "-Mdawqllf_-BaW63gMMM",
"text": "Finish the backend[1]",
"status": true,
"time": 1625248047800
},
{
"id": "-Mdawqllf_-BaW63gGHf",
"text": "Finish the middle-end[2]",
"status": false,
"time": 1625248040000
},
{
"id": "-Mdawqllf_-BaW63gGHd",
"text": "Finish the front-end[3]",
"status": false,
"time": 1625248040000
}
];
const todos = {
Todos: Object.fromEntries(data.map(obj => [obj.id, obj]))
};
console.log(todos);
#Barmar's solutions is nice.
For the sake of learning or others googling. You can also reduce the array to an object.
const todos = data.reduce((obj, item) => {
obj[item.id] = item
return obj
}, {})
const items = {
todos: {
...data
}
};
Assume that data is the array of objects.
Use the spread operator to copy all the array objects from data array to the todos object at key todos.
One important thing to note that you can't assign more than one objects without array to a single object key. You definately have to use the array to maintain all the objects under the one key.
Avoid using the hardcode index. Always use the spread operator

How to get JSON entry from returned objects

I got JSON data, like:
{
"id": 1,
"active": true,
"dependency": [
{ "id": 2 }
{ "id": 3 }
]
},
{
"id": 2,
"active": true
},
{
"id": 3,
"active": true
}
I want to retrieve the "active" value for each dependency in the id 1 object. So far I used a forEach to get those dependency.
thisElement.dependency.forEach(function(id) {
console.log(id)
}
Which returns id 2 and id 3 as objects. Is there a way to use id.active straight away? By using only one loop? Because the result so far are objects without any connection to the related JSON data. Would it require to loop through the whole JSON data to retrieve those values?
The most efficient thing to to is create a hashmap with an Object or Map first so you only need to iterate the array once to find dependency related values.
You could do it by using Array#find() to search whole array each time but that is far more time complexity than the o(1) object lookup
const activeMap = new Map(data.map(obj => [obj.id, obj.active]))
data[0].dependency.forEach(({id}) => console.log(id ,' active: ' , activeMap.get(id)))
<script>
const data =
[
{
"id": 1,
"active": true,
"dependency": [
{"id": 2 },
{"id": 3}
]
},
{
"id": 2,
"active": false
},
{
"id": 3,
"active": true
}
]
</script>

Change in array format

I want to create a array structure with child entities like this ->
$scope.groups = [
{
"categories": [
{
"name": "PR",
"sortOrder": 0,
"type": "category"
}
],
"name": "DEPT 1",
"sortOrder": 0,
"type": "group",
"id": "-JY_1unVDQ5XKTK87DjN",
"editing": false
}
];
from an array that dosen't have child entities but all the items are listed in one object like this->
$scope.groups = [
{
"name": "PR",
"sortOrder": 0,
"type": "category"
},
{
"name": "AD",
"sortOrder": 3,
"type": "category"
},
{
"name": "DEPT 2",
"sortOrder": 1,
"type": "group",
"id": "-JYZomQKCVseJmaZoIF9",
"editing": false,
"categories": []
},
];
Is there any possible way?
As #Eagle1 has rightly pointed out. You need to define your data model properly to define a function that does that grouping for you. That said, from what I understand you have a $scope.groups array of objects for a specific department containing some categories which you need to consolidate as a child element.
You could start by defining a function that returns an object like you mention:
var organize = function(arr){
cats = [];
dep = {};
$.each( arr, function( i, val ) {
if(val.type == "category")
cats.push(val);
else
dep = val;
});
dep.categories = cats;
return dep;
}
Ultimately, you'll have to traverse the array and look for objects of type category and dump them in an array and have that array as the categories key of the object that you intend to return. I hope it gets you started in the right direction.
of course it is.
It's doable in javascipt although to help you devise something we would need a relationship between categories.
However, that's sounds like something that should be done in your data model (a relationship between dept - category, classic reflexive relationship parent - children). angular should be receiving from the back end an array already ordered.

Categories

Resources