0

I have an object defined like this:

import React, { Component } from 'react';
import './App.css';

class App extends Component {

  constructor() {
    super();
    this.state = {
    lists: ["Dogs", "Cats"],
    items: {Dogs:[], Cats:[]}
    };
  }

  handleAddItem(item) {
    console.log(item);
  }

I have the variable

console.log(item);// output {Dogs:[{name: "lofi"}]}  

I don't know how to verify which property is in the item (Dogs or Cats) so that I can update the object items{} to make it becоme in my example like this:

items{Dogs:[{name: "lofi"}], Cats:[]}
1
  • What do you mean with verify? Commented Jun 5, 2018 at 12:25

2 Answers 2

1

You can use Object.keys method.

items[Object.keys(item)[0]] = item[Object.keys(item)[0]]

Working solution

let state = {
   lists: ["Dogs", "Cats"],
   items: {Dogs:[], Cats:[]}
};

let item = { Dogs:[{name: "lofi"}] };
state.items[Object.keys(item)[0]] = item[Object.keys(item)[0]]
console.log(state.items);

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

1 Comment

I can't use '{ Dogs: [ {name: "lofi"} ] }' explicitly, I have to use the object 'item' and look for the same property in 'items' to update
1

You can use Object.assign function on the state.items, which will add/update the given object with the properties given at the second parameter.

let state = {
   lists: ["Dogs", "Cats"],
   items: { Dogs:[], Cats:[] }
};

let item = { Dogs: [ {name: "lofi"} ] };

Object.assign(state.items, item);

console.log(state);

4 Comments

I can't use '{ Dogs: [ {name: "lofi"} ] }' explicitly, I have to use the object 'item' and look for the same property in 'items' to update.
Will your item contain either Dogs or Cats?
yes, both Dogs or Cats or even other animals that I can add
You don't need to know what is in the item, it just gets the properties from that and put them into the state.items

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.