Actually I'm trying to get all the value of object1 and get true if Like object has some id that match with current user id
Array [
Object {
"id": "-MgFbI5wXjtjKln1Wkqe",
"like": Object {
"-MgpHytKWNplejaxtLLF": "-MgpHytKWNplejaxtLLF",
},
"likes_count": 7,
},
Object {
"id": "-MgpHytKWNplejaxtLLF",
"like": Object {
"-MgFbI5wXjtjKln1Wkqe": "aC9dL88GCAXdnGyefY1XDiXd7Iu1",
},
"likes_count": 0,
},
]
Here is my code, arr contains whole object that are given above
const us = arr.map((item) => {
return item.like;
});
const ik = us.includes(uid);
console.log("snap ", ik);
I want given below object that include like variable true if like object have user id otherwise it assign false
Array [
Object {
"id": "-MgFbI5wXjtjKln1Wkqe",
"like":false,
"likes_count": 7,
},
Object {
"id": "-MgpHytKWNplejaxtLLF",
"like":true,
"likes_count": 0,
},
]
const us =Array(); // us is the final table that you need
for(i=0;i<arr.length;i++){
us[i]= {
"id":arr[i].id,
"like": arr[i].like===uid?true:false,
"likes_count": arr[i].likes_count,
}
}
or this :
const us = Array();// us is the final table that you need
arr.forEach((element,index) => us[index] = {
"id":arr[index].id,
"like": arr[index].like===uid?true:false,
"likes_count": arr[index].likes_count,} );
Related
I am building a Blog app and I am trying to get results but it is showing duplicate results, I am trying to remove the duplicate results from the array.
But the problem is there are two key and values in each dict inside array, One is unique and other can be same so I am trying to distinct based on same array, It worked But the other key and value pair (which is unique) is not attaching with the other pair.
response which is returning from db
[
{
"id": 2,
"name": "user_1"
},
{
"id": 3,
"name": "user_3"
},
{
"id": 4,
"name": "user_3"
}
]
App.js
function App() {
const [blogs, setBlogs] = useState([]);
axios.get("retract_blogs/").then((res) => {
// Here I also want to attach "id"
setBlogs({[...new Set(res.data.data.map(x => x.name))]})
}
return(
<div>
{
blogs.map((user) =>
<div>
{user.name}
// Here I wamt to show ID
// {user.id}
</div>
}
</div>
)
}
I want to add id with x.username, I also tried using
setBlogs({data:[...new Set(res.data.data.map(x => x.name, x.id))]})
But it showed
x is not defined
But I am trying to add both name and id, and remove duplicates based on name not id.
I have tried many times but it is still not working.
To keep the id of the last occurence you can create a Map of the array keyed by name and then convert back to an array using the iterator returned by Map.values(). This works by overwriting earlier entries in the Map with the same name.
const users = [{ "id": 2, "name": "user_1" }, { "id": 3, "name": "user_3" }, { "id": 4, "name": "user_3" }];
const result = [...new Map(users.map((user) => [user.name, user])).values()];
console.log(result);
// [ { id: 2, name: 'user_1' }, { id: 4, name: 'user_3' } ]
If you instead want to keep the id of the first occurence of a name you can use a slightly modified 'group by' grouping into an object by name (here in a reduce() call, but it could easily be done in a standard loop as well) before taking the Object.values. This works by only setting the accumulator[name] property if it doesn't already exist, here using logical nullish assignment (??=)
const users = [{ "id": 2, "name": "user_1" }, { "id": 3, "name": "user_3" }, { "id": 4, "name": "user_3" }];
const result = Object.values(users.reduce((a, c) => (a[c.name] ??= c, a), {}));
console.log(result);
// [ { id: 2, name: 'user_1' }, { id: 3, name: 'user_3' } ]
I want to loop through 600+ array items in an object and find one particular item based on certain criteria. The array in the object is called "operations" and its items are arrays themselves.
My goal is to get the index of operation's array item which has the deeply nested string "Go".
In the sample below this would be the first element. My problem is that I can check if an array element contains "call" and "draw" but I don't know how to test for the nested dictionary "foobar". I only have basic JavaScript available, no special libraries.
let json = {
"head": {},
"operations": [
[
"call",
"w40",
"draw",
{
"parent": "w39",
"style": [
"PUSH"
],
"index": 0,
"text": "Modify"
}
],
[
"call",
"w83.gc",
"draw",
{
"foobar": [
["beginPath"],
[
"rect",
0,
0,
245,
80
],
["fill"],
[
"fillText",
"Go",
123,
24
],
[
"drawImage",
"rwt-resources/c8af.png",
]
]
}
],
[
"create",
"w39",
"rwt.widgets.Menu",
{
"parent": "w35",
"style": [
"POP_UP"
]
}
],
[
"call",
"w39",
"draw",
{
"parent": "w35",
"style": [
"POP_UP"
]
}
]
]
};
let index = "";
let operationList = json.operations;
for (i = 0; i < operationList.length; i++) {
if (operationList[i].includes('call') && operationList[i].includes('draw')) //missing another check if the dictionary "foobar" exists in this element )
{
index = i;
}
}
document.write(index)
I'll preface by saying that this data structure is going to be tough to manage in general. I would suggest a scheme for where an operation is an object with well defined properties, rather than just an "array of stuff".
That said, you can use recursion to search the array.
If any value in the array is another array, continue with the next level of recursion
If any value is an object, search its values
const isPlainObject = require('is-plain-object');
const containsTerm = (value, term) => {
// if value is an object, search its values
if (isPlainObject(value)) {
value = Object.values(value);
}
// if value is an array, search within it
if (Array.isArray(value)) {
return value.find((element) => {
return containsTerm(element, term);
});
}
// otherwise, value is a primitive, so check if it matches
return value === term;
};
const index = object.operations.findIndex((operation) => {
return containsTerm(operation, 'Go');
});
I am trying to figure out an easy way to convert an array of objects to an object
I have an array of objects that looks like this:
[
{
"id": "-LP9_kAbqnsQwXq0oGDT",
"value": Object {
"date": 1541482236000,
"title": "First",
},
},
.... more objects here
]
And id like to convert it to an object with the timestamps as the keys, and arrays of objects corresponding to that date. If that key already exists, then add the object to the corresponding array associated with that key
{
1541482236000:
[{
"id": "-LP9_kAbqnsQwXq0oGDT",
"value": Object {
"date": 1541482236000,
"title": "First",
},
},
{
"id": "-LP9_kAbqnsQwXqZZZZ",
"value": Object {
"date": 1541482236000,
"title": "Some other title",
},
},
.... more objects here
],
1541482236001:
[{
"id": "-LP9_kAbqnsQ1234",
"value": Object {
"date": 1541482236001,
"title": "Another title",
},
},
.... more objects here
]
}
I was able to achieve something similar using reduce. However it does not handle adding objects to the array when their key already exists.
calendarReminders = action.value.reduce((obj, reminder) => {
dateKey = moment(reminder.value.date).format('YYYY-MM-DD')
obj[dateKey] = [reminder]
return obj;
}, {});
How can I do this?
You just need to check whether the object is already a key and if not add it with the value of an array. Then you can just push() into it:
let arr = [{"id": "-LP9_kAbqnsQwXq0oGDT","value": {"date": 1541482236000,"title": "First",},},{"id": "SomID","value": {"date": 1541482236000,"title": "Some other title",},},{"id": "A different ID","value": {"date": 1541482236001,"title": "A third title",},}]
let calendarReminders = arr.reduce((obj, reminder) => {
(obj[reminder.value.date] || (obj[reminder.value.date] = [])).push(reminder)
return obj;
}, {});
console.log(calendarReminders)
If you want to set the keys to a different format with moment, you should be able to do that without changing the basic idea.
Please test the below code!
First you iterate through your array of data,
if your result object/dictionary already has the key then you just add the current item
otherwise you make the key and set the value
const data = [];
let result = {};
for (const item of data) {
const key = item.value.date;
if (result.hasOwnProperty(key)) {
const prevData = result[key];
result[key] = [...prevData, item];
} else {
result[key] = [item];
}
}
I need to iterate this json and push the values into an other array
[
{
"id": 1,
"nombre": "Samson",
"marcaModelo": [
{
"id": 6,
"nombre": "API 6D "
}
]
}
{
"id": 6,
"nombre": "Endress + Hauser",
"marcaModelo": [
{
"id": 10,
"nombre": "Proline t-mass 65F50-AK2AH1RCBBCA"
},
{
"id": 8,
"nombre": "Cerabar M"
}
]
}
]
I made out with this
Object.entries(res).forEach((value, key) => {
console.log(key, value)
this.marcas.push({
'marcaId': res[key].id,
'marcaNombre': res[key].nombre,
'modeloId': res[key].marcaModelo[0].id,
'modeloNombre': res[key].marcaModelo[0].nombre
})
console.log(this.marcas)
})
but only push one marcaModelo object into marcas array, if I replace marcaModelo[0] for marcaModelo[key] I get an undefined.
I need something like this
{
marcaId:6
marcaNombre:"Endress + Hauser"
modeloId:[10, 8]
modeloNombre:[Proline t-mass 65F50-AK2AH1RCBBCA, Cerabar M]
}
You need a nested loop for all the marcaModelo objects; you can use .map() to return an array of the results of a function on each element.. It also doesn't seem like you need to use Object.entries(). The original object is an array, you can use .forEach() directly on it.
res.forEach(value => {
console.log(value);
this.marcas.push({
'marcaId': value.id,
'marcaNombre': value.nombre,
'modeloId': value.marcaModelo.map(o => o.id),
'modeloNombre': value.marcaModelo.map(o => o.nombre)
});
console.log(this.marcas);
}
or
res.map(({ id, nombre, marcaModelo }) => ({
marcaId: id,
marcaNombre: nombre,
modeloId: marcaModelo.map(m => m.id),
modeloNombre: marcaModelo.map(m => m.nombre),
}));
I have the following array containing objects, And there are arrays in the objects too.
let array = [
{
"data": {
"Game": {
"Game_number": [
"4",
"6",
"8"
],
"Game_name": [
"Name_1",
"Name_2",
"name_3"
]
},
"AA": {
"AA_count": [
"30"
],
"AA_name": [
"Umbrella"
]
},
}
}
]
Now i have to put them in database, Each have a column against.
But the issue is that the above data is not constant, So i cannot put them via their indexes. if the data is missing for a column than that's fine it will go empty
I tried via for each but that is inserting the last element of the array.
array.data.forEach((item) => {
const Games = Parse.Object.extend('Games');
const query = new Games();
item.data.Game.Game_number.forEach((number) => {
query.set('game_number', number);
}, this);
item.data.Game.Game_name.forEach((name) => {
query.set('game_name', name);
}, this);
query.save();
}, this);
What will be a flexible way to handle it ?