按照自定义顺序连接存在的对象字符串值



我被传递了一个包含地址数据的对象(按字母顺序),我想提取一个子集来显示,但以不同的顺序。

不是所有的键在任何时候都有数据,有时会有一个空字符串而不是什么都没有。

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

我知道我可以通过以下方式得到所有的现值:

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

然而,我希望输出的信息顺序为:company, buildingName, streetName, townCity, county, postCode.

是否有任何方法可以改变我当前的解决方案,或者我是否需要完全不同的方法?

我在某种程度上结合了Jan Pfeifer和Gog的解决方案,并进行了自己的实验。

没有值的字段也不是作为空字符串返回,但不包括在内,因此使事情变得简单一些。

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});

如果这是更长或更复杂的,我会考虑通过将filetermap合并成reduce来进行整理,但我认为目前还没有必要这样做。

因为需要自定义订单,所以必须手动创建该对象。您可以使用模板数组,但这或多或少是相同的解决方案。

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);

您可以创建一个addressOrder数组,指定各种地址组件的顺序,然后使用Array.reduce()添加到输出地址组件。

我们只会将地址添加到输出中,如果它存在于address对象中。

最后,我们将使用提供的分隔符连接地址组件。

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

相关内容

  • 没有找到相关文章