JavaScript - store disassembled objects in a fresh variable

I'm working on implementing Destructing on a variable, inspired by the example found in MDN:

 var 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
    }
];

for (var {name: n, family: {father: f}} of people) {
  console.log('Name: ' + n + ', Father: ' + f);
  //Store results in a new variable here
}

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

The code above generates two lines in a loop. I am looking to save the content produced by the for-in loop into a fresh variable so that I can transmit it from the server (using Express.js) to the client.

Answer №1

If you're following along, it seems like all you have to do is add it to an array (or something similar):

var people = [
    {
        name: 'Emily Johnson',
        family: {
            mother: 'Maria Johnson',
            father: 'John Johnson',
            sister: 'Lily Johnson'
        },
        age: 30
    },
    {
        name: 'David Brown',
        family: {
            mother: 'Sarah Brown',
            father: 'Michael Brown',
            brother: 'James Brown'
        },
        age: 28
    }
];

var results = [];

for (var {name: n, family: {father: f}} of people) {
    results.push({ n, f });
}

console.log(JSON.stringify(results));
// => [{"n":"Emily Johnson","f":"John Johnson"},{"n":"David Brown","f":"Michael Brown"}]

https://jsfiddle.net/xyzabc123/1/

Answer №2

Here is a suggestion to consider:

let output = [];
for (var {first: fname, last: {father: dad}} of individuals) {
  const data = 'First Name: ' + fname + ', Father\'s Name: ' + dad;
  console.log(data);
  output.push(data);
  //Store results in a variable here
}
console.log('output', output);

Now you have an array of information that you can manipulate as needed.

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

Refresh all div elements if included in the results of the $.ajax call

My ajax function retrieves html content with div elements. However, Internet Explorer tends to include comments in the result array without an id, leading to errors like "object doesn't support this property or method". Removing the comments resolves ...

Sending data from a parent component to a child component through a function

In the process of developing an app, I have implemented a feature where users must select options from four dropdown menus. Upon clicking the "OK" button, I aim to send all the selections to a child component for chart creation. Initially, I passed the sel ...

Is there any purpose to incorporating an AngularJS directive within a comment?

Hello, I'm curious about the purpose of using an AngularJS directive as a comment. I've seen some examples where it can display an alert message, even with arguments, but I'm struggling to see the practical use of a directive as a comment. C ...

Discover the paths to locate all keys within an object that correspond to a specified string

I need help creating a function in plain JavaScript that can find all paths to keys with a specific name in an object. The object may have repeated key names at different depths. Here is an example: const obj = { stuff: { A: 'text' ...

The canvas doesn't seem to be rotating even after executing the setTransform

Within my HTML5 canvas, I have been experimenting with drawing lines and rotating them around the center point. My goal is to reset the canvas's transformation each time I draw, followed by re-translating/rotating the canvas. However, I have encounter ...

Unresolved issue with AngularJS radio button binding

As a beginner in using Angular.js, I encountered an issue with data binding when dealing with radio buttons. The HTML code in question is: <label class="options_box" ng-repeat="item in item_config_list.item_config"> <input type="radio" name ...

Obtaining the access token from the URL: A step-by-step guide

Once I have successfully authenticated with Google, the URL I receive is: http://localhost:3000/_oauth/google#access_token=ya29.5HxuYol1Io8JLeGePDznbfkkwu_PC4uodKwG8_1clFYAn9AgdOV1WGpOTNQP3s76HAsn7Y4zWw&token_type=Bearer&expires_in=3600 I am tryi ...

Obtaining the pathname in a NextJS file like _document.js is a matter of accessing

I'm looking to retrieve the current URL path in my /page/_document.js file. I've created a class and my goal is to implement a conditional statement based on this value. Below is the code snippet (similar to the example provided in NextJS docume ...

Errors occur when attempting to install plugins from npm

I am currently coding in Visual Studio 2017 using Ionic v2 to develop an app for beacon scanning. However, every time I try to install a plugin, I encounter errors from npm about the versions of node and npm being incompatible. Here are my current versions ...

Importing arrays from one file to another in JavaScript

Imagine you have a file named file1.js containing an array. var array = [data, more data, ...]; Are there any methods to access this array from another file? If not, what are the typical practices for managing a large array within a file? ...

Unable to resize images in Firefox

Why is it that resizing doesn't seem to work in Firefox but functions fine in Internet Explorer? I'm struggling to find a way to make it consistent across all browsers. My goal is to resize the width to 800 and height to 475, disable maximizing t ...

JavaScript does not function properly when interacting with the result of a POST request made through $.ajax

Question: After including jQuery files and functions in index.php, do I also need to include them in select.php? To clarify my issue, here is the problem I am facing: Initially, I am trying to send data to select.php using jQuery's $.ajax. The data ...

Display collection in Vue app

I am working with a model called files, which includes a property named response containing an array called errorMessages. In my Vue component, I am looking for a way to display these errors individually rather than as an array. Is there a solution for thi ...

How can I add text to a textbox within a duplicated div using Javascript or Jquery?

I'm looking to add text to a cloned div's text box using jQuery. I have a div with a button and text box, and by cloning it, I want to dynamically insert text into the new div. $(document).ready(function () { $("#click").click(function () { ...

How to handle a Vue element click event through programming

In my Vue instance, I am looking to have a response triggered by a click on an uploaded thumbnail. Utilizing the Vue package called FineUploader Vue with the template layout as outlined in the documentation (refer to end of question). After uploading an i ...

Determine the total number of selected items in MagicSuggest when it loses focus

I have been working with MagicSuggest and I am currently facing an issue where I need to retrieve the length of selections on a blur event. Interestingly, my code functions perfectly fine when a new selection is added using the ENTER key, but it fails when ...

AngularJS and adding to an array in the routing process

I'm currently working on creating a contact list with two different views. One view displays all the contacts and includes an option to add a new contact, which is represented by a button rather than a space to input information directly. The other vi ...

Utilizing the Bing Translation API to translate an entire webpage

I am currently attempting to use the Bing API to translate an entire webpage instead of using the Bing widget. This is because I want to create a custom design for the translation panel, However, I have been unable to find any resources on how to do this ...

Errors can occur in React/Axios when API calls are served over HTTP instead of HTTPS

I'm currently utilizing an API to retrieve movie data by making use of axios within my React application. This functionality is operating as intended in my local environment; however, when I deployed the app to github pages, it ceased to function prop ...

`<picture> contains the main image``

Is it possible to access the currently displayed source of a <picture> element in JavaScript without relying on viewport width or pixel density? Looking for a method similar to <select>:selected If anyone has insights on this, please share! ...