Unpack and retrieve multiple values

Currently diving into the world of JavaScript and exploring destructuring. My goal is to display the following in the console:

"Name: Mike Smith, Father: Harry Smith"

"Name: Tom Jones, Father: Richard Jones"

Encountering an error message stating n is not defined, even though it should be fine? Here's the code snippet I've been working on:

const people = [
  {
    name: 'Mike Smith',
    family: {
      mother: 'Jane Smith',
      father: 'Harry Smith',
      sister: 'Samantha Smith'
    },
    age: 35
  },
  {
    name: 'Tom Jones',
    family: {
      mother: 'Norah Jones',
      father: 'Richard Jones',
      brother: 'Howard Jones'
    },
    age: 25
  }
];

const kalle= people.map(( {name: n, family: {father: f}})=> { 
return [n,f]
});
  
console.log('Name: ' + n + ', Father: ' + f);

// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"

Answer №1

n and f are located outside the function, meaning they cannot be accessed directly. Instead, loop over the array to access them.

When destructuring objects, a key is not necessary unless the value itself is an object.

const people = [
  {
    name: 'Mike Smith',
    family: {
      mother: 'Jane Smith',
      father: 'Harry Smith',
      sister: 'Samantha Smith'
    },
    age: 35
  },
  {
    name: 'Tom Jones',
    family: {
      mother: 'Norah Jones',
      father: 'Richard Jones',
      brother: 'Howard Jones'
    },
    age: 25
  }
];

// Returns an array
const persons = people.map(({name, family: {father}})=> { 
  return [name, father];
});

// Log each person
persons.forEach(([name, father]) => {
  console.log(`Name: ${name}, Father: ${father}`);
});

// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"

Answer №2

Using a simple join function can give you the result you're looking for.

const people = [
  {
    name: "Mike Smith",
    family: {
      mother: "Jane Smith",
      father: "Harry Smith",
      sister: "Samantha Smith",
    },
    age: 35,
  },
  {
    name: "Tom Jones",
    family: {
      mother: "Norah Jones",
      father: "Richard Jones",
      brother: "Howard Jones",
    },
    age: 25,
  },
]

const kalle = people
  .map(({ name: n, family: { father: f } }) => {
    return "Name: " + n + ", Father: " + f
  })
  .join("\n")

console.log(kalle)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Draggable HighStock element causing issues with Gridster dragging

I have integrated a stocks chart from HighStocks with gridster, where each gridster block is draggable. However, the stocks time slider gadget can also be dragged and resized. When I move the slider on top of a gridster widget, the entire widget moves alon ...

Submitting content to numerous webpages

I'm looking to submit form data on multiple pages, while keeping the main action as "". After clicking, I want the page to refresh but also send the POST data to another .php file. This is necessary because the other .php file generates a graph that ...

Capturing link titles for control navigation in Nivo Slider

Essentially, in the nivoslider plugin, the controlnav section displays numbers based on the "rel" attribute in the code. I am wondering if there is a way to modify this so that it retrieves the "title" or "alt" from the link added to the slideshow. This wo ...

Click on the React interface to add the elements to an array

I have a task to generate an array when clicking on a specific div element, which represents a product card. class Card extends Component { constructor(props){ super(props) this.state = { likesArr: [] } } // Function for handling ...

Issue with VueJS instance: Unable to prevent default behavior of an event

Is there a way to disable form submission when the enter key is pressed? Take a look at the different methods I've attempted along with the code and demo example provided below. SEE PROBLEM DEMO HERE Intended outcome: When you focus on the input, pr ...

what is the best way to center list items in material ui?

I have been attempting to align the list items (checkbox, text, and buttons) within a Material UI list in the center, but all my attempts have been unsuccessful. Is there anyone who knows how to resolve this issue? Your help would be greatly appreciated! h ...

Amend and refresh information using AJAX technology

My code isn't working as expected when I try to use AJAX to retrieve data from an editable form and update it in the database. Can someone help me find the issue? Below is the code I'm using: <?php $query = db_get_list("SELECT * FROM ...

Retrieving a file URL from Sanity within a blocks array

I've been working on a website with Next JS and using Sanity as the CMS. While Sanity has schemas for images, I ran into an issue when trying to handle videos. The documentation recommends using GROQ queries to convert file URLs at the request level, ...

Is there a way to automatically fill in a text field when an option is chosen from a dropdown menu populated with a list of objects?

When working with a DTO that has attributes id, name, and text, I am creating a list of these DTOs and passing them to my JSP using model.addAttribute. In the JSP, I am rendering a Spring list in the following way: <form:select path="notificationsId" i ...

What is the simplest way to transform a JSON containing strings into a JSON with arrays?

I am tasked with creating a method named public string PrepareForDeserialization(string json) that will transform a JSON string such as: {"To":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2ccc3cfc7e2c1cdcfd2c3ccdb8cc1cdcf" ...

Determine the maximum value in an array using recursive Java function

Can someone assist me with using recursion to find the largest number in an array? I am currently not achieving the desired results and any guidance would be greatly appreciated. public class ArrayMax { public static int largestNumber(int[] array) { ...

Using Jquery to assign negative values in CSS styling

Here is the jQuery code snippet I am working with: <script type="text/javascript" src="js/jquery.js"> </script> <script type="text/javascript"> $(document).ready(function() { get_font_size(); set_sidebar(); }); function get_f ...

Combining JSON array objects in Vanilla Javascript to create a nested array based on a shared value

I have been searching for a solution to address my specific issue but have not found an exact match. If there is a similar question, please provide a link to the solution. I am looking to merge an array of objects that share a common value using vanilla J ...

What steps do I need to take to create an animation where an outline gradually becomes filled in

I've been experimenting with creating a loading animation inspired by the pre-loading animation on this website. My attempt using chat GPT resulted in an unexpected outcome where, instead of filling the SVG, it placed a black square on top of it. The ...

Exploring Array/Json Objects with PHP: A Guide to Iterating Through

My array contains various nodes. When I print it using print_r($cruise), here is what the array looks like: Array ( [SearchCruise_ApiInfoResponse] => Array ( [SearchCruise_ApiInfoResult] => {"TirunServer": [{"Sail_Date":"11/10/2020","Nights":"22","B ...

Experiencing difficulties when establishing a connection between MongoDB and Node.js

I'm encountering an issue when attempting to connect MongoDB and Node.js on my local server. Can anyone assist me with solving this problem? Below is my JavaScript code: const mongodb = require("mongodb"); // Provide the function to connect to the d ...

Encountering an error while trying to install with npm: getting an error message that says "Cannot read property '

Encountering a puzzling error during the installation process with `npm install`, even though it functions properly on other devices. NPM and Node versions: C:\Users\Work>npm -v 8.3.2 C:\Users\Work>node -v v14.16.1 Presenting t ...

Updating values using events within a v-for loop in a Vue template: A step-by-step guide

Just starting out with Vue and Laravel! Currently, I am retrieving data from an API Resource in Laravel. The API consists of 2 fields: Goal Value Here is the code snippet: <template> <div class="container"> <h1> Progress ...

Error message occurs when attempting to access an array generated from JSON data

Today, I've been experimenting with JSON, PHP, and JS, but I'm encountering some issues. The PHP code functions correctly, retrieving a row of data from my SQL table and encoding it as JSON. My JS/JQuery script successfully loads the data from t ...

What is the best way to access and utilize variables passed in an app.post request within another app.post request using Node.js

I have encountered an issue with using const variables in my app.post method. I defined these variables to store user input when submitting a form, but when attempting to send the variables back to the user for verification in my app.post method, it throws ...