Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to get an object's own keyname to use within the object?

for example, can ‘dliaz’ be pulled into img: to be used rather than typing the same thing out twice for every object?

const profileContentSrc={
    'dliaz':{
        img:img_root[0]+'dliaz'+img_root[1],
        p:'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nec felis consectetur, semper urna nec, eleifend sapien.'
    },    
    'srojourner':{
        img:img_root[0]+'srojourner'+img_root[1],
        p:'Morbi hendrerit dignissim lorem, id scelerisque elit. Aliquam iaculis varius lacinia. In dignissim placerat urna ac hendrerit.'
    }  

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can do it if you first create an auxiliary data object (or if you already have a set of entries in your database) and then generate a final object out of it using for loop. For example:

var img_root = [
    'user-',
    '.jpg'
];  // for example

var data = [
    {
        name: 'dliaz',
        text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nec felis consectetur, semper urna nec, eleifend sapien.'
    },
    {
        name: 'srojourner',
        text: 'Morbi hendrerit dignissim lorem, id scelerisque elit. Aliquam iaculis varius lacinia. In dignissim placerat urna ac hendrerit.'
    }
];

function getDataObject(array) {
    var obj = {};
    for (var item of array) {
        obj[item.name] = {
            img: img_root[0] + item.name + img_root[1],
            p: item.text
        };
    }
    return obj;
}

console.log(getDataObject(data));

Good luck!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading