I have this array of objects from an api:
"use strict";
var data = [{
"OPEN COVER (YES or NO)": "YES"
}, {
"OPEN COVER (YES or NO)": "NO"
}, {
"OPEN COVER (YES or NO)": "YES"
}];
var result = [];
data.map(function (item) {
var fixed = {};
var keys = Object.keys(item);
keys.map(function (key) {
if (key === 'OPEN COVER (YES or NO)') return fixed['open_cover'] = item[key];
});
result.push(fixed);
});
console.log(result);
I have this array of objects from an api:
"use strict";
var data = [{
"OPEN COVER (YES or NO)": "YES"
}, {
"OPEN COVER (YES or NO)": "NO"
}, {
"OPEN COVER (YES or NO)": "YES"
}];
var result = [];
data.map(function (item) {
var fixed = {};
var keys = Object.keys(item);
keys.map(function (key) {
if (key === 'OPEN COVER (YES or NO)') return fixed['open_cover'] = item[key];
});
result.push(fixed);
});
console.log(result);
How do i change the value from "YES" to true and "NO" to true?
Share Improve this question asked May 21, 2018 at 20:04 Abel MasilaAbel Masila 7712 gold badges7 silver badges25 bronze badges4 Answers
Reset to default 3You can easily convert a 'YES' to true
and 'NO' to false
using a ternary. Also, you can use a forEach
instead of a map
:
"use strict";
var data = [{
"OPEN COVER (YES or NO)": "YES"
}, {
"OPEN COVER (YES or NO)": "NO"
}, {
"OPEN COVER (YES or NO)": "YES"
}];
var result = data.reduce(function(items, item) {
var fixed = {};
var keys = Object.keys(item);
keys.forEach(function(key) {
if (key === 'OPEN COVER (YES or NO)') {
return fixed['open_cover'] = item[key] === 'YES';
}
});
items.push(fixed);
return items;
}, []);
console.log(result);
If you could use ES6 features, use map to iterates and returns a new array, creating a new object with spread operator for each array item
"use strict";
var data = [{
"OPEN COVER (YES or NO)": "YES"
}, {
"OPEN COVER (YES or NO)": "NO"
}, {
"OPEN COVER (YES or NO)": "YES"
}];
const key = 'OPEN COVER (YES or NO)';
const result = data.map( item => {
return {
...item,
...{
[key]: item[key] === 'YES'
}
}
});
console.log(result);
Working fiddle, based on Chase DeAnda's original answer https://jsfiddle/xctohpw5/
Or something like this, assuming that you will always have fixed key name "OPEN COVER (YES or NO)"
:
"use strict";
var data = [{
"OPEN COVER (YES or NO)": "YES"
}, {
"OPEN COVER (YES or NO)": "NO"
}, {
"OPEN COVER (YES or NO)": "YES"
}];
var result = data.map(function (item) {
var tempObj = {};
var key = Object.keys(item)[0];
var value = item[key] === 'YES';
tempObj[key] = value;
return tempObj;
});
console.log(result);
The easiest way to do this would be to set the value to a simple statement.
fixed['open_cover'] = item[key] === "YES"
This will check if item[key]
is equal to "YES"
and set your output to true
or false
.