如何在JavaScript中将字符串转换为对象数组

7

我想将这个字符串Option 1|false|Option 2|false|Option 3|false|Option 4|true转换为以下形式的对象数组

在JavaScript Nodejs中是否有可能实现?谢谢提前。

[
  {
    "option": "Option 1",
    "value": false
  },
  {
    "option": "Option 2",
    "value": false
  },
  {
    "option": "Option 3",
    "value": false
  },
  {
    "option": "Option 4",
    "value": true
  }
]

2
我喜欢一行代码.... const result = "Option 1|false|Option 2|false|Option 3|false|Option 4|true".split('|').map((option, i, a) => i % 2 ? null : {option, value: a[i+1]}).filter(x => x) - Jaromanda X
6个回答

15

您可以将数组拆分并进行迭代。

const
    string = 'Option 1|false|Option 2|false|Option 3|false|Option 4|true',
    result = [];

for (let i = 0, a = string.split('|'); i < a.length; i += 2) {
    const
        option = a[i],
        value = JSON.parse(a[i + 1]);
    result.push({ option, value });
}

console.log(result);


3
有趣的是,这位“减少皇后”这次使用了for循环。但是如果您跳过每个第二个元素,可能会更快。 - yunzen

4

您可以使用正则表达式在字符串上使用.match()函数来得到一个形如以下的数组:

[["Option 1", "false"], ...]

然后将每个键值对映射到一个对象中,如下所示:

const str = "Option 1|false|Option 2|false|Option 3|false|Option 4|true";
const res = str.match(/[^\|]+\|[^\|]+/g).map(
  s => (([option, value]) => ({option, value: value==="true"}))(s.split('|'))
);

console.log(res);


3

const options = 'Option 1|false|Option 2|false|Option 3|false|Option 4|true';

const parseOptions = options => options.split('|').reduce((results, item, index) => {
  if (index % 2 === 0) {
    results.push({ option: item });
  } else {
    results[results.length - 1].value = item === 'true';
  }
  return results;
}, []);

console.log(parseOptions(options));


2

str='Option 1|false|Option 2|false|Option 3|false|Option 4|true';
str=str.split('|');
result=[];
for(var i=0;i<str.length;i += 2){
result.push({"option":str[i],"value":str[i+1]=="true"?true:false})
}
console.log(result)


1
str[i+1]=="true"已经可以得到相同的结果,因此这里不需要三元运算符。 - Adrian Brand

2
我有一个稍微更为实用的解决方案,我认为它更具语义化。
const str = 'Option 1|false|Option 2|false|Option 3|false|Option 4|true';
const parsed = str
    .match(/[^\|]+\|[^\|]+/g)
    .map(matchedValues => {
        const [option, value] = matchedValues.split('|');
        return Object.fromEntries([['option', option], ['value', JSON.parse(value)]]);
    })

console.log(parsed);


1
好的,我加了 JSON.parse 但是想法还是一样的。 - Enslev

0
使用Array.prototype.reduce,您可以将从String.prototype.split得到的数组转换为对象。

const str = "Option 1|false|Option 2|false|Option 3|false|Option 4|true";
const arr = str.split('|')

const obj = arr.reduce((carry, elem, index, orig) => {
  if (index % 2) { return carry }
  carry.push({"option": orig[index], "value": !!orig[index+1]});
  return carry;
}, [])

console.log(obj)

或者采用双重分割的更为奇特的方法

const str = "Option 1|false|Option 2|false|Option 3|false|Option 4|true";
const arr = (str+"|").match(/[^|]+\|[^|]+(?=\|)/g);

const res = arr.reduce((carry, item) => {
  let [option, value] = item.split('|');
  carry.push({option, value: !!value});
  return carry;
}, [])

console.log(res)


@JaromandaX 你说得对。我编辑了我的回答。没有仔细阅读原帖。 - yunzen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接