Combine the string values of objects in a specific order where they exist

I have received an object with address details in alphabetical order that I need to extract a specific subset from and display them in a different sequence.

Some keys may have an empty string instead of no data at all.

const address = {
  buildingName: '',
  company: 'My org',
  county: 'My County',
  postCode: 'My Postcode',
  streetName: 'My street',
  townCity: 'My Town'
};

I am aware that I can retrieve all values by using:

Object.keys(address).filter(Boolean).join(', ')

However, I want the information to be displayed in the following order:

company, buildingName, streetName, townCity, county, postCode
.

Is there a way for me to modify my current solution or should I consider a different approach?

Answer №1

If you require a custom order, you will need to manually create the object. One option is to use a template array, which provides a similar solution.

const address = {
    buildingName: '',
    company: 'My org',
    county: 'My County',
    postCode: 'My Postcode',
    streetName: 'My street',
    townCity: 'My Town'
};

const tmp = ["company", "buildingName", "streetName", "townCity", "county", "postCode"];
let s = "";
tmp.forEach(key => {
    const v = address[key];
    if(v) {
        if(s) s += ", ";
        s += v;
    }
});
console.log(s);

Answer №2

To establish a specific order for address components, consider creating an array called addressOrder. Then utilize the Array.reduce() method to assemble the output address.

The address will only be included in the final output if it exists within the address object.

Lastly, combine the address components using the designated delimiter.

const address = {
  buildingName: 'Nakatomi Towers',
  company: 'Nakatomi Corp.',
  county: 'LA County',
  postCode: '90067',
  streetName: 'Century City',
  townCity: 'LA'
};

function formatAddress(address, addressOrder, delimiter = ', ') { 
    return addressOrder.reduce((outputFields, field) => { 
        if (address[field]) {
            outputFields.push(address[field]);  
        }
        return outputFields;
    }, []).join(delimiter);
}

const order1 = ['company','buildingName','streetName','townCity','county','postCode']
const order2 = ['buildingName','streetName','townCity','postCode']

console.log('Address:', formatAddress(address, order1))
console.log('\nAddress (alt. format):\n' + formatAddress(address, order2, '\n'))
.as-console-wrapper { max-height: 100% !important; }

Answer №3

After experimenting with Jan Pfeifer and Gog's solutions, I was able to create a solution that worked for my needs.

I discovered that fields without values were not returned as empty strings but were simply omitted, which actually made things easier.

const ADDRESS_ORDER = ['company', 'buildingName', 'streetName', 'townCity', 'county', 'postCode'];

return const addressString = ADDRESS_ORDER
    .filter(detail => Object.keys(address).includes(detail))
    .map(key => address[key])
    .join(', ');

const ADDRESS_ORDER = ['company', 'buildingName', 'streetName', 'townCity', 'county', 'postCode'];

const address = {
  company: 'My org',
  county: 'My County',
  postCode: 'My Postcode',
  streetName: 'My street',
  townCity: 'My Town'
};

const result = ADDRESS_ORDER
    .filter(detail => Object.keys(address).includes(detail))
    .map(key => address[key])
    .join(', ');
    
console.log({result});

If this task became more complex, I might consider consolidating the filter and map into a reduce, but for now, it seems unnecessary.

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

Navigating C pointers with casting types

#include<stdio.h> int main() { int a; char *x; x = (char *) &a; a = 512; x[0] = 1; x[1] = 2; printf("%d\n",a); return 0; } I'm struggling to understand how the output ends up being 513 or if i ...

What is the process to subscribe and obtain data from a server-to-user channel using pusher-js?

I am currently hosting my application using next.js on Vercel. I want to integrate Pusher to provide real-time messages to users in a private and secure manner. Despite successful log entries, I am facing challenges in subscribing to the channel and retrie ...

What are the best practices for implementing media queries in Next.js 13.4?

My media queries are not working in my next.js project. Here is what I have tried so far: I added my queries in "styles.module.css" and "global.css" and imported them in layout.js I included the viewport meta tag under a Head tag in layout.js This is how ...

Choosing a default selection in a nested v-for loop for a select box

Currently, I have a list of items that users can add new items to. Each item is required to have a select box, and the selected value from the select box should be assigned as the item's value. In an attempt to bind the select box to the item using t ...

What is the most efficient way to traverse two or more lists in linear time complexity?

I'm facing a challenging question that seems impossible for me to solve. I have multiple arrays (2+) and need to compare them for common values while minimizing the number of comparisons to O(N). Specifically, I have to achieve (k-1)N comparisons wher ...

Declaration of String Arrays

I'm encountering a frustrating problem that should be simple. Java arrays can be quite tricky and not very intuitive. One specific String array I have is called 'title' and it contains various titles. Here is a snippet of the array: p ...

Issue found in React Js test - TypeError: source.on does not exist as a function

I'm encountering an issue with my post request using multipart/form-data. Everything runs smoothly, except for the tests which are failing. When running the tests, I encounter an error message: TypeError: source.on is not a function. This is the code ...

Are the Node.JS environment variables missing?

In my Node.JS application, I have set up some crucial environmental variables in the .env file, such as AUTH0_CLIENT_ID and AUTH0_CLIENT_SECRET. To enable Auth0 support on the client side, I included the following code: var jwt = require('express-jw ...

Tips for creating a responsive carousel slider for images

No matter how much I've tried, I can't seem to find a solution on how to make my image responsive along with the caption. Below is my HTML code: <section id="banner"> <div class="banner-bg"> <div class="banner-bg-item ...

Task on arrays in C programming for homework

I created a program where users can choose to either add a class, drop a class, or print an invoice. The classes are stored as arrays. My issue lies with the invoice generation. I have two functions that retrieve the course name and course credits in order ...

unique jquery plugin accesses function from external javascript file

As a beginner, I am attempting to create a custom jQuery plugin for which I have a simple HTML form: <form id="registerForm" action = "somepage" method="post" class="mb-sm"> <div class="form-group"> <div class="col-md-12"> ...

Switching from class components to function components in Ant Design

I attempted to convert this code into a functional component, but encountered some roadblocks. import ReactDOM from 'react-dom'; import 'antd/dist/antd.css'; import './index.css'; import { Tag, Input, Tooltip } from 'antd ...

Tips for toggling the visibility of a flexbox-styled popup using jQuery

I am trying to implement a popup on my website and I want to use flexbox styling for it. I have the necessary scss mixins for flexbox properties, however, I encountered an issue. The problem arises when I try to hide the popup using display: none, as the ...

Exploring the magic of Hover effects using CSS and JQuery

I am exploring ways to enhance the display of an element when hovering over it. I have implemented a button and my objective is for the first click to activate the hover effect, while the second click will reset it. However, I am facing an issue where the ...

Using an object to set formData

Currently, I am facing an issue with my state and formData. When I type some text, instead of changing fullName.firstName, it creates another property and sets a single letter value. https://i.sstatic.net/kZQJy.png const [formData, setFormData] = useStat ...

Tips on updating checkbox background color after being selected

I've been working on creating checkboxes for seat selection in Angular using a TypeScript file, but I'm facing an issue where the background color of the checkbox doesn't change after checking them. Here's my TypeScript function: gener ...

How to bypass or exclude a value in a numpy array?

I am working with pixel values stored in a h5 file, extracting the data and creating a histogram using numpy. The array contains a specific no-data value of 99999, whereas the rest of the data ranges from -40 to 20. To ensure the no-data value does not aff ...

"Having an issue with the jQuery AJAX call where the success function is not operating as expected

I attempted to retrieve information from a database using PHP by making an AJAX call with jQuery. However, I encountered an issue where the $.ajax function was not functioning as expected. There were no error messages displayed, and the console.log('s ...

Exclude specific keys from an array

I am currently filling out forms using an array. Everything is functioning correctly, but now I need to temporarily remove certain keys from the array for specific fields. After processing those fields, I will need to restore the keys with their original v ...

Launching shuttles using HTML and JavaScript

I've been working on an HTML code with JavaScript for a platform validation project. Over the last couple of weeks, I've been diligently coding and testing to ensure everything runs smoothly. However, my code suddenly stopped responding, leaving ...