简体   繁体   中英

console.log the name and the day of this object

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.

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

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 .

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

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