【问题标题】:How to get all keys except a certain one in Object.keys?如何在 Object.keys 中获取除某个键之外的所有键?
【发布时间】:2020-03-14 04:19:36
【问题描述】:

如何获取除某个键之外的所有键? 我想获取除“Id”之外的所有键,如何跳过?

我的代码:

const [newContact, setNewContact] = useState({
        id: 1,
        name: {
            value: '',
            type: "text",
            label: "Фио",
            placeholder: "Фио"
        },
        phone: {
            value: '',
            type: "text",
            label: "Номер",
            placeholder: "Номер"
        }
    });

const onHandleRenderInputs = () => {
    return Object.keys(newContact).map((input, index) => {
        const inputControl = newContact[input];
        return (
            <Form.Item label={inputControl.label} style={{display: "flex", flexDirection: "column", alignItems: "flex-start" }} key={index + input}>
                <Input
                    type={inputControl.type}
                    placeholder={inputControl.placeholder}
                    value={inputControl.value} 
                    onChange={e => onHandleSigninUserData(input, e)}
                />
            </Form.Item>
        );
    });
};

我使用Object.keys()创建输入,但我不需要所有字段,只需要“姓名”和“电话”,我怎么能只取它们?

【问题讨论】:

  • 当你迭代你的键时,只需检查键值,如果它是你想要改变的东西,然后做你的逻辑。否则,不要做任何事情。或者使用hasOwnProperty.. 专门搜索对象上的这些键

标签: reactjs key


【解决方案1】:

在将每个项目映射到输入控件之前,您应该 filter Object.keys 数组。例如。

const onHandleRenderInputs = () => {
    return Object.keys(newContact).filter(i=> i !== 'id').map((input, index) => {
        const inputControl = newContact[input];
        return (
            <Form.Item label={inputControl.label} style={{display: "flex", flexDirection: "column", alignItems: "flex-start" }} key={index + input}>
                <Input
                    type={inputControl.type}
                    placeholder={inputControl.placeholder}
                    value={inputControl.value} 
                    onChange={e => onHandleSigninUserData(input, e)}
                />
            </Form.Item>
        );
    });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 2015-03-06
    • 2023-04-07
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多