jsDev
jsDev

Reputation: 166

How to create a single object from key-value pairs objects in JavaScript?

I have several objects and I want to create another one that will have keys from a particular array (const props = []), and values from those objects - if it only exists in those objects, but if not - I want to push null or some other fake values.

My code:

const props = ["name", "price", "qty", "category"]
let len = props.length;

const obj_1 = {
  name: "Product_1",
  price: 120,
  category: 'phone'
}

const obj_2 = {
  name: "Product_2",
  price: 7893,
  category: 'program_eq',
  qty: 5
}

const final_obj = {
  name: ["Product_1", "Product_2"],
  price: [120, 7893],
  category: ["phone", "program_eq"],
  qty: [null, 5]
}

I have spent lots of time with this problem and have some solution - but it gives me only the first object. I am using lodash/map and it helps me to work with different type of collection.

You can see my solution bellow:

const final_obj = {};
    const props = ["name", "price", "qty", "category"];
    let len = props.length;

    const obj = {
      c1s6c156a1cascascas: {
        item: {
          name: "Product_1",
          price: 120,
          category: "phone"
        }
      },
      c454asc5515as41cas78: {
        item: {
          name: "Product_2",
          price: 7893,
          category: "program_eq",
          qty: 5
        }
      }
    };

    _.map(obj, (element, key) => {
      console.log(element.item);
      while (len) {
        let temp = props.shift();
        let tempData = [];
        if (element.item.hasOwnProperty([temp])) {
          tempData.push(element.item[temp]);
        } else {
          tempData.push("---");
        }
        final_obj[temp] = tempData;
        len--;
      }
    });
    console.log(final_obj); 
    
    //
    category:["phone"]
    name:["Product_1"],
    price:[120],
    qty:["---"],

Upvotes: 2

Views: 1125

Answers (3)

acontell
acontell

Reputation: 6922

You can do as well using some lodash functions.

Transform the array of props into an object which keys are the values of props and which values are extracted from the object. If the property doesn't exist in the object, return null.

const getValFromObj = (obj, key) => _.map(obj, _.partial(_.get, _, key, null));
const setValInResult = (res, key) => _.set(res, key, getValFromObj(obj, 'item.' + key));
const groupByProps = (props, obj) => _.transform(props, setValInResult, {});

const props = ["name", "price", "qty", "category"];
const obj = {
  "c1s6c156a1cascascas": {
    "item": {
      "name": "Product_1",
      "price": 120,
      "category": "phone"
    }
  },
  "c454asc5515as41cas78": {
    "item": {
      "name": "Product_2",
      "price": 7893,
      "category": "program_eq",
      "qty": 5
    }
  }
}

console.log(groupByProps(props, obj));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Upvotes: 0

pixelscript
pixelscript

Reputation: 392

This is how I would handle it:

const final_obj = { };
const props = ["name", "price", "qty", "category"];
const obj = {"c1s6c156a1cascascas":{"item":{"name":"Product_1","price":120,"category":"phone"}},"c454asc5515as41cas78":{"item":{"name":"Product_2","price":7893,"category":"program_eq","qty":5}}}

// set up each property as an empty array in the object
props.forEach(item => {
    final_obj[item] = [];
});

// this iterates over every property in the object
_.forOwn(obj, value => {
    props.forEach(item => {
        // just push the values undefined or no into each property array
        final_obj[item].push(value.item[item]);
    });
});
console.log(final_obj);

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122047

You could do this with reduce() method that will return object and inside use forEach() loop.

const props = ["name", "price", "qty", "category"];
const obj = {"c1s6c156a1cascascas":{"item":{"name":"Product_1","price":120,"category":"phone"}},"c454asc5515as41cas78":{"item":{"name":"Product_2","price":7893,"category":"program_eq","qty":5}}}

const result = Object.values(obj).reduce((r, e) => {
  props.forEach(prop => {
    if(!r[prop]) r[prop] = []
    r[prop].push(e.item[prop] || null)
  })
  return r;
}, {})

console.log(result)

Upvotes: 1

Related Questions