简体   繁体   English

Javascript - 如何从正则表达式返回字符串而不是 [Object object]

[英]Javascript - How to return a string from a regex instead of [Object object]

I have a parent form component and a child component which I'm using for auto-completing text input.我有一个父表单组件和一个子组件,用于自动完成文本输入。 I'm passing an array of objects called autoCompTxt that has a name and id field, from the Parent component to the Child component.我正在将一个名为 autoCompTxt 的对象数组从父组件传递到子组件,该数组具有名称和 id 字段。

//Parent:
const [obj, setObj] = useState([{name:'',id:''}]);
<AutoCompleteText onChange={text => setName(text)} autoCompTxt={obj} name="sampleName" id="sampleId" />

In the child component I'm trying to filter on the name string, using 'v.name'.在子组件中,我尝试使用“v.name”过滤名称字符串。 But the suggestions array gets populated with Objects instead of Strings.但是建议数组填充的是对象而不是字符串。

//Child:
let suggestions = [];
suggestions = props.autoCompTxt.sort().filter(v => regex.test(v.name));
console.log(suggestions);

AutoCompleteText.js:22 Suggestions: [object Object],[object Object] AutoCompleteText.js:22 建议:[object Object],[object Object]

I've tried using JSON.stringify() and ${v.name} .我试过使用 JSON.stringify() 和${v.name} But they haven't helped.但他们没有帮助。

The issue is that the line below is returning 2 objects.问题是下面的行返回 2 个对象。 {name:"name1", id:1},{name:"name2", id:2} {name:"name1", id:1},{name:"name2", id:2}

instead of returning just the names.而不是只返回名称。 "name1","name2" “名称 1”、“名称 2”

suggestions = props.autoCompTxt.sort().filter(v => regex.test(v.name));建议 = props.autoCompTxt.sort().filter(v => regex.test(v.name));

import React from 'react';
import { useState } from 'react';
import { Input } from 'reactstrap';
const AutoCompleteText = props => {

    const [suggestions, setSuggestions] = useState([]);
    const [text, setText] = useState('');

    const onTextChanged = (e) => {
        const value = e.target.value;

        let suggestions = [];

        if (value.length > 0) {
            setSuggestions([]);
            const regex = new RegExp(`^${value}`, 'i');
            console.table(props);
            suggestions = props.autoCompTxt.sort().filter(v => regex.test(v.name));
            console.log('Suggestions: ' + suggestions);

        }
        setSuggestions(suggestions);
        setText(value);
    }

    function suggestionSelected(value) {
        setSuggestions([]);
        props.onChange(value);
        setText(value);
    }

    function renderSuggestions() {
        if (suggestions.length === 0) {
            console.log(suggestions);
            return null;
        }
        return (
            <ul>
                {suggestions.map((item) => <li onClick={() => suggestionSelected(item)}>{item}</li>)}
            </ul>
        )
    }

    return (
        <div>
            <Input value={text} onChange={onTextChanged} type="text" />
            {renderSuggestions()}

        </div>
    )
};

export default AutoCompleteText;

If you want an array of strings (v.name) after filtering, map a new array:如果要过滤后的字符串数组(v.name),map 一个新数组:

suggestions = props.autoCompTxt
              .sort()
              .filter(v => regex.test(v.name))
              .map(v => v.name);

The problem is in render suggestion you cannot pass an object directly to dom, you need to pass only one value问题在于渲染建议您不能将 object 直接传递给 dom,您只需要传递一个值

            <ul>
                {suggestions.map((item) => <li onClick={() =>suggestionSelected(item)} key={item.id}>
                {item.name}
                 </li>)}
            </ul>

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

相关问题 使用正则表达式或替代方法从字符串返回一个 javascript 对象 - Return a javascript object from string using Regex or alternative methods 如何使用javascript正确返回对象而不是函数? - How to correctly return an object instead of function with javascript? 如何使用nock返回对象而不是字符串以进行响应? - How to return object instead of string for response with nock? AngularJS如何返回字符串而不是Json对象 - AngularJS how return a string instead of Json object 将以字符串形式返回的正则表达式从API转换为JavaScript中的有效RegEx对象 - Turning a regex returned as a string from an API into a valid RegEx object in JavaScript 如何在javascript中返回带有对象的字符串? - How do I return a string with an object in javascript? JavaScript字符串而不是预期的对象 - Javascript string instead of object expected 如何从在javascript中返回对象的函数返回元素对象? - How to return element object from a function that return an object in javascript? JavaScript输出[object,object]而不是字符串 - JavaScript outputting [object, object] instead of string 如何使用jquery或javascript从对象内部将当前对象作为JSON字符串返回? - How can I return the current object as a JSON string from inside the object with jquery or javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM