Home > Software engineering >  How to add items to a list and order by property in React or React Native
How to add items to a list and order by property in React or React Native

Time:11-27

I am hoping to put my json data in a list and then add objects to the list and order everything by location

const [list, setList] = useState([])

const blocks = 4

const placeholder = [{ action : null, location : null, title : null }]

const json = [
  {
    "action": "go back",
    "location": 0,
    "title": "first Demo"
  },
  {
    "action": "press go",
    "location": 2,
    "title": "Second"
  }
]

Output I am hoping for when I console.log(list)

[
  {
    "action": "go back",
    "location": 0,
    "title": "first Demo"
  },
  {
    "action": "none",
    "location": 1,
    "title": "first Demo"
  }, 
  {
    "action": "press go",
    "location": 2,
    "title": "Second"
  },
  {
    "action": "none",
    "location": 3,
    "title": "first Demo"
  }
]

What I have tried. It works but wanted a better way to do it

const jsonValue = await AsyncStorage.getItem('@custom_layout');
      if (jsonValue != null) {
        const createPallet = Array.from({length: blocks}, (v, i) => ({
          title: null,
          icon: null,
          UUID: i,
          location: i,
          Children: [],
          action: null,
        }));

        JSON.parse(jsonValue).map((item, i) => {
          //Find index of specific object using findIndex method.
          const objIndex = createPallet.findIndex(
            obj => obj.location === item.location,
          );

          //Update object's.
          createPallet[objIndex] = item;

          // This will update your state and re-render
          setItems([...createPallet]);
        });

Basically we get a count of the blocks. Then we reorder the json by location. If there is a gap from 0-3 fill it in with placeholder data

CodePudding user response:

Where you set the variable list const [list, setList] = useState([]) you are actually setting it to an empty array []. But that's just a point about terminology. You can sort the array using a sort function as follows. But bear with me, I'm going to rename it array.

const [array, setArray] = useState([]);

//Now you can add missing blocks.
for(let i=0; i<blocks; i  ){
   if(!json.find(element=>element.location==i)){
      const newplaceholder = placeholder[0];
      newplaceholder.location = i;
      json.push(newplaceholder)
   }
}


//This is your sort function
const sortArray = (a, b)=>{
   return a.location-b.location
}

//When you want to use it to sort the array
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
json.sort(sortArray)

//Once you've added the placeholders and sorted the array
setArray(json);


  • Related