Home > Mobile >  console.log the name and the day of this object
console.log the name and the day of this object

Time:12-10

How can get this if I want to console.log only the Names and the day just like this:

 [Name1: {
     day: 'Successfully Graphed'
},
 Name2: {
     day: 'Successfully Graphed'
},
 Name3: {
     day: 'Successfully Graphed'
}
 Name4: {
     day: 'Successfully Graphed'
}],

in this array of objects.

[Name1: {
    day: 'successfully graphed',
    week: 'successfully graphed',
    month: 'successfully graphed',
    year: 'successfully graphed'
},
Name2: {
    day: 'successfully graphed',
    week: 'successfully graphed',
    month: 'successfully graphed',
    year: 'successfully graphed'
},
Name3: {
    day: 'successfully graphed',
    week: 'successfully graphed',
    month: 'successfully graphed',
    year: 'successfully graphed'
},
Name4: {
    day: 'successfully graphed',
    week: 'successfully graphed',
    month: 'successfully graphed',
    year: 'successfully graphed'
}],

I tried to get it by

console.log(result.data);

but when I make it as

console.log(result.data.name.day);

it will become undefined.

CodePudding user response:

convert array obj to object and then try it will work .

var array = [
    {key:'k1',value:'v1'},
    {key:'k2',value:'v2'},
    {key:'k3',value:'v3'}
];
var mapped = array .map(item => ({ [item.key]: item.value }) );
var newObj = Object.assign({}, ...mapped );
console.log(newObj );

CodePudding user response:

Assuming result.data is an array of your objects:

The reason you're getting undefined because name doesn't exist on your result (as the object keys are actually called "Name1", "Name2", etc).

If possible (and perhaps out of scope of the question), I'd change the result.data to return in this format:

results.data:
[
 {
    id (or name): <whatever value you want>
    day: 'successfully graphed',
    week: 'successfully graphed',
    month: 'successfully graphed',
    year: 'successfully graphed'
 },
...
],

Then you could simply do a map over the results like so:

const mappedResults=results.data.map(nameObject=>({name:id,day}))

If you are unable to change the structure of the results, my suggestion would be to convert the data to an object as per this answer.

CodePudding user response:

Firstly convert the data into array of objects.

let array = [
    {key:'k1',value:'v1'},
    {key:'k2',value:'v2'},
    {key:'k3',value:'v3'}
];

And then you would be able to fetch the key from this array

  • Related