打字稿添加单个项目到对象数组

时间:2019-03-01 19:24:34

标签: javascript

我正在尝试转换以下函数,以接受在输入字段中输入的行。如果有多行,它可以正常工作;如果有换行符“ \ n”,我正在将条目读取到数组中,但我不知道如何在没有换行符的情况下获取格式化单个条目的格式数组项:

  const obj = {};
  Object.keys(value).map(function(data) {
    if (data !== 'submit') {
      const val: string = value[data].toString();
      let result = val;
      // this is accounting for line breaks
      if (val.indexOf('\n') > 0) {

        //multiple lines, being added into array correctly 
        result = JSON.parse(JSON.stringify(val.split('\n')));

      } else {

        //problem is here, need result as a single item in an array
        result = JSON.parse(JSON.stringify(val));
      }
      obj[data] = result;
    }
  });

2 个答案:

答案 0 :(得分:2)

可能需要将val转换为数组。 JSON.parse(JSON.stringify([val]));

答案 1 :(得分:0)

这项工作有效吗?用[]

将单个项目包装在数组中
const obj = {};
      Object.keys(value).map(function(data) {
            if (data !== 'submit') {
                const val: string = value[data].toString();
                let result = val;
                // this is accounting for line breaks
                if (val.indexOf('\n') > 0) {
                    //multiple lines, being added into array correctly 
                    result = JSON.parse(JSON.stringify(val.split('\n')));
                } else {
                    //problem is here, need result as a single item in an array
                    result = JSON.parse(JSON.stringify([val]));
                }
            obj[data] = result;
      }
  });
相关问题