简体   繁体   English

将具有键值对的字符串映射到对象

[英]Mapping string with key-value pair to object

Given the following string with key-value pairs, how would you write a generic function to map it to an object? 给定以下带有键值对的字符串,您将如何编写一个泛型函数将其映射到对象?

At the moment, I am just splitting by : and ; 此刻,我只是按:; to get the relevant data, but it doesn't seem like a clean approach. 获取相关数据,但这似乎不是一种干净的方法。

This my code at the moment: 此刻我的代码:

var pd = `id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74`;
var tempPd = pd.split(';');
for (i = 1; i < tempPd.length; i++) {
    var b = tempPd[i].split(':');
    console.log(b[1]);
}

What about using reduce: 如何使用reduce:

 function objectify(str) { return str.split(";").reduce(function (obj, item) { var a = item.split(":"); obj[a[0]] = a[1]; return obj; }, {}); } var strObj = "id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74"; console.log(objectify(strObj)); 

or: 要么:

 function objectify(str){ return str.split(";").reduce((obj,item)=>{ var a = item.split(":"); obj[a[0]]=a[1]; return obj; },{}); } var strObj = "id:S76519;sku:S76519;name:StarGazer 3000;model:ICC74"; console.log(objectify(strObj)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM