how to add elements to array using push [duplicate] - javascript

This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 1 year ago.
Having issues with array data
OUT PUTTING LIKE THIS
[{
"createdAt": [Object],
"date": "2021-08-22",
"description": "Yes"
}, {
"title": "greatt"
}
I need it to output like this below
[{
"createdAt": [Object],
"date": "2021-08-22",
"description": "Yes",
"title": "greatt"
}
const myList = [];
myList.push(otherArray, {title: 'Hello'})

The result you're getting indicates that otherArray is not an array, it's a single object
{
"createdAt": [Object],
"date": "2021-08-22",
"description": "Yes"
}
So you're pushing two separate objects onto myList.
If you want to merge an object into another object, you can use Object.assign().
Object.assign(otherArray, {title: 'Hello'});
Then you can do
myList.push(otherArray);
to add that object to the myList array.

I think what you want to do is push the extra object values inside the last object of the array ! So here's the solution for that =>
let array = [{
"createdAt": [Object],
"date": "2021-08-22",
"description": "Yes"
}]
function push(props , array) {
let lastIndex = array.length - 1;
array[lastIndex] = Object.assign(props, array[lastIndex]);
}
push({
title: "Title"
}, array);
console.log(array)
For more information about Object.assign checkout MDN

Related

Go through arrays of objects that contain arrays of objects

Backend sends an object that contains an array of objects. These objects contain more arrays of objects and so on. It resembles a tree.
I need to be able to go from one object to the other, following the array, and back. What would be the best way to do this in typescript?
I tried forEach, but I couldn't go back. For cycles inside of for cycles aren't an option either because sometimes there will be 2 levels of arrays, sometimes, 5. I thought of an iterator, but I don't know enough of angular/typescript to make it happen.
Here is a snippet of the data. This is a questionnaire and I need to show each question individually.
"questionId": 1,
"parent": null,
"description": "Question 1?",
"children":
[
{
"questionId": 2,
"parent": 1,
"description": "Question 2?",
"children":
[
{
"questionId": 4,
"parent": 2,
"description": "Question 4?",
"children": []
}
]
},
{
"questionId": 3,
"parent": 1,
"description": "Question 3?",
"children": []
}
]
Sorry if I'm explaining it poorly or something is missing, I'm not used to post here.
If you just want to iterate through all the question objects, you could try to flatten your data with a recursive function like this,
const flattenQs = (qData) => {
const flattenedQs = []
flattenedQs.push({questionId: qData.questionId, parent: qData.parent, description: qData.description})
for (let i = 0; i < qData.children.length; i++) {
const qChild = qData.children[i];
flattenedQs.push(...flattenQs(qChild))
}
return flattenedQs
}
Which would give something like this,
[
{
questionId:1,
parent:null,
description:"Question 1?"
},
{
questionId:2,
parent:1,
description:"Question 2?"
},
{
questionId:4,
parent:2,
description:"Question 4?"
},
{
questionId:3,
parent:1,
description:"Question 3?"
}
]

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

map and find the names of all objects [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 1 year ago.
I wanted to map all the names and power of the objects and if he finds an array inside gadgets he would add +1 (i++), how would that be?
The list is much bigger, but I just show these two
"list": [
{
"name": "SHELLY",
"power": 10,
"gadgets": [
{
"id": 23000255,
"name": "FAST FORWARD"
}
]
},
{
"name": "COLT",
"power": 7,
"gadgets": [
{
"id": 23000273,
"name": "SPEEDLOADER"
},
{
"id": 23000319,
"name": "SILVER BULLET"
}
]
]
}
A simple map should do it:
const data = {list:[{name:"SHELLY",power:10,gadgets:[{id:23000255,name:"FAST FORWARD"}]},{name:"COLT",power:7,gadgets:[{id:23000273,name:"SPEEDLOADER"},{id:23000319,name:"SILVER BULLET"}]}]};
const res = data.list.map(p => ({
name: p.name,
power: p.power + p.gadgets.length
}));
console.log(res);

Loop into Array of Objects comparing two arrays - PUG (Jade)

I am trying in Javascript, using PUG template (if possible), to compare two arrays and when I find a correspondance in IDs, display some particular elements.
// First Array : I iterate over "hearts" object
// Called in PUG : - const user
[
{
"hearts": [
"5e70c63a94b27b164c9b897f",
"5e723c75e4bfdf4f58c55e32"
],
"_id": "5e6bb1189978fd5afc98c57a",
"email": "catherine#catherine.com",
"name": "Catherine",
"photo": "0121b7fe-b2ae-4e75-979d-7dea1a432855.jpeg",
"__v": 0
},
{
"hearts": [
"5e723c75e4bfdf4f58c55e32"
],
"_id": "5e6bc41f5915e3d2980a5174",
"email": "marc#marc.com",
"name": "Marc",
"photo": "4caa7bfb-6408-4893-a78b-fa6e8e5b03e7.png",
"__v": 0
}
]
// Second array : I iterate over "author.hearts" object
// Called in PUG : - const store
[{
"product": {
"categories": [
1,
2
]
},
"_id": "5e6bcc76c4022eae00e22af6",
"date": "2222-02-20T21:22:00.000Z",
"author": {
"hearts": [
"5e723c75e4bfdf4f58c55e32",
"5e70c63a94b27b164c9b897f"
],
"_id": "5e6bb1189978fd5afc98c57a",
"__v": 0
},
"created": "2020-03-13T18:09:58.086Z",
"id": "5e6bcc76c4022eae00e22af6"
}]
I want to loop over the first array, find the first ID (here 5e70c63a94b27b164c9b897f), loop over the second array and see if this ID is present within the "author.hearts" object. If it is not, carry on with the second ID and if it is present, display all the keys (tags, photos, _id, date...) from the object where the ID was found.
In my example, I have just one object in my array, but I'll be having much more later on.
Many thanks for your help
If I'm understanding correctly you can do something like this. Loop through all your users and when you find their id in author.hearts stop the loop there and return the object the user's _id was found in.
var resultFound = undefined;
try {
user.forEach((el) => {
const id = el._id;
const result = store.find(el => el.author.hearts.includes(id));
if (result) {
resultFound = result;
throw resultFound;
}
});
} catch (e) {
if (e !== resultFound) {
throw e;
}
}

Accessing value in nested object [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I don't understand how I can access an value in a object that is an array with an object inside itself.
I've tried with the dot notation and [] and array.reduce. But I'm doing something wrong.
I've changed the values but the structure remains the same:
"test": {
"title": "My title",
"category": null,
"info": [{
"time": 10,
"type": "minutes"
}]
}
I need to get the values of time and type, but I get undefined.
The final object is first element of array so you need to first access its first element.
const obj = {
"test": {
"title": "My title",
"category": null,
"info": [{
"time": 10,
"type": "minutes"
}]
}
}
console.log(obj.test.info[0].time);
console.log(obj.test.info[0].type);
Use the dot notation to access the properties
Object a consists of the test object which in-turn contains the key info whose value is an array containing one object with the required keys
a->test->info->[{time,type}]
var a = {
"test": {
"title": "My title",
"category": null,
"info": [{
"time": 10,
"type": "minutes"
}]
}
}
console.log(a.test.info[0].time)
console.log(a.test.info[0].type)

Categories

Resources