1

In React I have a state:

const [selecteditems, setSelectedItems] = useState()

On form submit I have an object that looks like this {items: {item1: true, item2: true, item3: false}} I need to turn this object into an array of objects that looks like this: [{ name: 'item1', price: ''}, {name: 'item2', price: ''}] to use with setSelectedItems

Then I would like to be able to update prices of individual items using setSelectedItems. How would I achieve this?

To recap, first I need to convert an object into an array of objects, then I need to update individual price values in the array of objects separately.

0

4 Answers 4

2

You can use filter and map. For updating an object, find can be used.

const obj = {items: {item1: true, item2: true, item3: false}};
const res = Object.entries(obj.items).filter(([k,v]) => v)
    .map(([k]) => ({name: k, price: ''}));
console.log(res);
//update
let name = 'item2';
res.find(x => x.name === name).price = '$10';
console.log(res);

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

Comments

1

Or you can use reduce() also.

const value = {items: {item1: true, item2: true, item3: false}} 
// [{ name: 'item1', price: ''}, {name: 'item2', price''}]


const res = Object.entries(value.items).reduce((acc, [k,v]) => {
  return v ? acc.concat({ name: k, price: '' }) : acc;
},[])

console.log(res);

Comments

1
    const items = {items: {item1: true, item2: true, item3: false}}
    const itemArray = [];
    Object.keys(items.items).forEach((key) => {
      if (items.items[key])
        itemArray.push({
          name: key,
          price: '',
        });
    });

    setSelectedItems(itemArrary);

Update price

    const name = 'item1';

    const _itemArray = [...itemArray];
    const index = _itemArray.findIndex(item => item.name === name);

    if (index !== -1) {
        _itemArray[index].price = '$100';
        setSelectedItems(_itemArray);
    }

Comments

0

you can to this

const price = [{ name: 'item1', price: ''}, {name: 'item2', price: ''}]

const newPrice = {
name: "item1",
price: "$1000"
}

const results = price.map((x) => x.name === "item1" ? newPrice : x)
console.log(results)

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.