React - convert object into array of objects with properties

后端 未结 4 950
时光说笑
时光说笑 2021-01-25 07:15

I have the following object

\"data\":{  
         \"name 1\":\"a\",
          \"name 2\":\"b\",
          \"name 3\":\"b\",
        },

How can

相关标签:
4条回答
  • 2021-01-25 07:41

    The solution provided by Tall Paul will work perfectly but you can also use Object.entries(). It states that

    The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

    so you can try something like this

    let result = Object.entries(data);
    result.map((item, index)=>{
          console.log('key is:- ', item[0], ' and value is:- ', item[1]); 
    });
    
    0 讨论(0)
  • 2021-01-25 07:41

    js native method u can use;

    var data = {  
         "name 1":"a",
          "name 2":"b",
          "name 3":"b",
        };
        var newObj = [...Object.values(data), ...Object.keys(data)]
        console.log(newObj)

    0 讨论(0)
  • 2021-01-25 07:54

    you can get all the keys in the object in an array using Object.keys function and use map function to get the desired output.

    This will convert to array of objects that will keep both the name and data.

    var data = {  
              "name 1":"a",
              "name 2":"b",
              "name 3":"b",
    }
    var res = Object.keys(data).map(function(name){
    	var obj = {};
    	obj[name] = data[name];
    	return obj;
    });
    
    console.log(res);

    0 讨论(0)
  • 2021-01-25 08:00

    If you use a reduce function you can do the following to achieve your goal

    Object.keys(data).reduce((array, key) => {
        return [...array, {key: data[key]}]
    }, [])
    

    Reduce is a cool function that iterates and combine data into one single item (could be 1 object, array, integer, etc).

    Object.keys() is a way to get each key from the current object and be able to iterate over each.

    0 讨论(0)
提交回复
热议问题