Search code examples
javascriptecmascript-6javascript-objects

How to store object full property in JavaScript


I think it might be silly question to ask but trust me I am new to JavaScript and I want to solve my problem . Actually , I have object and I am retrieving object value based on keys so here I want to store full object property ( mean with property name and it value ) . Currently when I console object it give me result look like :

Laundry Room: true
Lawn: true
Swimming Pool: true
Water: true 

when I try to console with Object.map method it just give true ( object value ) . I want to store full object property and value in variable like Laundry Room: true then console that variable .

My Code

   Object.keys(data).map(key => {
      if (data[key] === true) console.log(data[key]);
    });

Result with my code

true


Solution

  • This will give you expected output:
    

    const data = {
              "Laundry Room": true,
              "Lawn": false,
              "Swimming Pool": true,
              "Water": true,
              "parking": 2
            };
        const features = {};
        const newData = {};
        Object.keys(data).forEach(key => {
          if (data[key] === true){
            features[key] = data[key];
          }
          if (key === "parking"){
            features["parking_space"] = data[key];
          }
          else newData[key] = data[key];
        });
        newData["features"] = JSON.stringify(features);
        console.log(newData["features"]);

    <!-- end snippet -->