0

I want to loop an array inside a checkbox group from antd:

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Checkbox } from "antd";

function onChange(checkedValues) {
  console.log("checked = ", checkedValues);
}

const a = [
  { label: "Apple", value: "Apple" },
  { label: "Pear", value: "Pear" },
  { label: "Orange", value: "Orange" }
];
const optionsWithDisabled = [
  a.map((i) => ({ label: i.label, value: i.value }))
];

ReactDOM.render(
  <>
    <Checkbox.Group options={optionsWithDisabled} onChange={onChange} />
  </>,
  document.getElementById("container")
);

demo: https://codesandbox.io/s/checkbox-group-ant-design-demo-forked-j4tmk?file=/index.js:0-587
Now i get Cannot read property 'toString' of undefined , why?

1
  • 1
    Remove the square brackets around a.map(...) Commented Oct 27, 2020 at 21:09

1 Answer 1

1

Without having had a look at your component or know what it expects for the options prop the below code (yours) will give you a nested array which I don't think you want. That's because map will return an array.

const a = [
  { label: "Apple", value: "Apple" },
  { label: "Pear", value: "Pear" },
  { label: "Orange", value: "Orange" }
];
const optionsWithDisabled = [
  a.map((i) => ({ label: i.label, value: i.value }))
];

console.log(optionsWithDisabled)

You likely want something like this:

const a = [
  { label: "Apple", value: "Apple" },
  { label: "Pear", value: "Pear" },
  { label: "Orange", value: "Orange" }
];
const optionsWithDisabled = a.map((i) => ({ label: i.label, value: i.value }));

console.log(optionsWithDisabled)

And note that:

const optionsWithDisabled = a.map((i) => ({ label: i.label, value: i.value }));

is the same as:

const optionsWithDisabled = a;

But I assume you're doing other transformations there

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.