简体   繁体   中英

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:["---"],

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)

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);

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/lodash@4.17.5/lodash.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM