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

Time:09-21

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.'
    }  

CodePudding user response:

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!

  • Related