DEV Community

Dezina
Dezina

Posted on • Edited on

JS problems

1. How to add array to an object

<script>
// JavaScript program to add array into
// an object using push() function

// Creating a JS object to add array into
var Obj = {         
    arrayOne: ['Geeks', 'for', 'Geeks'],
    arrayTwo: []
};

// Array to be inserted
var arraynew = ['Hello', 'World', '!!!'];

// Pushing of array into arrayTwo
Obj['arrayTwo'].push(arraynew); 

alert(Obj.arrayTwo);

</script>                   

Enter fullscreen mode Exit fullscreen mode

2. Add & Delete dynamic input fields

 const inputArr = [
    {
      type: "time",
      id: 1,
      value: "",

    }
  ];

const [field, setField] = useState(inputArr);
const [tempfield, setTempfield] = useState("");

// Add input field
const addInputField = (e) => {
    e.preventDefault();

      setField(s => {
        const lastId = s[s.length - 1].id;
        const nextId = lastId + 1;
        console.log("lastId", lastId)
        return [
          ...s,
          {
            type: "time",
            id: nextId,
            value: tempfield
          }
        ];
      });
}

 // Delete the input field
  const deleteField = (fieldId) => {

  let filterField = field.filter(arr => arr.id !== fieldId + 1)
      setField(filterField)
}
Enter fullscreen mode Exit fullscreen mode

3. Checkboxes

 const [checked, setChecked] = useState(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])

  // Add/Remove checked item from list
  const handleCheck = (event) => {
    var updatedList = [...checked];
    if (event.target.checked) {
      updatedList = [...checked, event.target.value];
    } else {
      updatedList.splice(checked.indexOf(event.target.value), 1);
    }
    setChecked(updatedList);
  };

<div>
              <input
                className="form-check-input"
                value="Monday"
                type="checkbox"
                defaultChecked
                onChange={handleCheck} />
              Monday
</div>
Enter fullscreen mode Exit fullscreen mode

4. Find & replace array object

// can use find or map
 let find = cartData.find((o, i) => {
      if (o.product_id === pid) {
        // cartData[i] =
        //   { name: 'new string', value: 'this', other: 'that' };
        cartData[i].quantity += 1
        return true; // stop searching
      }
    });
    console.log("Replaced data", cartData)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)