This question already has answers here:
Iterate through object properties
(31 answers)
Closed 14 days ago.
The community reviewed whether to reopen this question 14 days ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
I have the below JSON response:
{
"A":{"Option1":true,"Option2":true,"Option3":false}
"B":{"OptionX":true,"OptionY":true,"OptionZ":false}
}
I want to get the following values in a string: Option1, Option2, OptionX, OptionY
I have tried the below but with no luck:
Array.from(this.model).forEach(child => {
console.log(child, 'child name')
});
Use flatMap() with filter() where you map over each key using Object.keys()
const data = {
"A": {"Option1":true,"Option2":true,"Option3":false},
"B": {"OptionX":true,"OptionY":true,"OptionZ":false}
};
const res = Object.values(data).flatMap(o => Object.keys(o).filter(k => o[k]));
console.log(res)
for (const record of Object.values(json)) {
for (const [key, value] of Object.entries(record)) {
if (value) {
console.log(key);
}
}
}
// or
const keys = Object
.values(json)
.map(record => Object
.entries(record)
.filter(([key, value]) => value)
.map(([key]) => key)
)
const obj = {
"A": {
"Option1": true,
"Option2": true,
"Option3": false
},
"B": {
"OptionX": true,
"OptionY": true,
"OptionZ": false
}
}
const result = Object.values(obj).flatMap(o => Object.entries(o).filter(([key, value]) => value).map(([key]) => key))
console.log(result)
Related
This question already has answers here:
Filter an array of objects by another object of filters
(4 answers)
Closed last year.
I'd like to filter this programs array (I've simplified the objects):
const programs = [
{
format: "In-Person",
schedule: "Full-Time",
},
{
format: "Remote",
schedule: "Full-Time",
},
{
format: "In-Person",
schedule: "Part-Time",
},
{
format: "Remote",
schedule: "Part-Time",
}
]
based on a filter object:
const filters = {format: "Remote", schedule:"Full-Time"}
My attempt:
let filteredPrograms = programs.filter((program) => {
return Object.entries(filters).every(([key, value]) => {
program[key] == value;
});
});
This should analyze each program, and allow is to pass through the filter IF:
For every filter key, the program[filter key] value matches the filter value
But I'm getting an empty array for filteredPrograms
Return the comparison result inside the every callback:
const programs=[{format:"In-Person",schedule:"Full-Time"},{format:"Remote",schedule:"Full-Time"},{format:"In-Person",schedule:"Part-Time"},{format:"Remote",schedule:"Part-Time"}],filters={format:"Remote",schedule:"Full-Time"};
let filteredPrograms = programs.filter((program) => {
return Object.entries(filters).every(([key, value]) => {
return program[key] == value;
});
});
console.log(filteredPrograms)
Or make it an arrow function:
const programs=[{format:"In-Person",schedule:"Full-Time"},{format:"Remote",schedule:"Full-Time"},{format:"In-Person",schedule:"Part-Time"},{format:"Remote",schedule:"Part-Time"}],filters={format:"Remote",schedule:"Full-Time"};
let filteredPrograms = programs.filter((program) => {
return Object.entries(filters).every(([key, value]) => program[key] == value);
});
console.log(filteredPrograms)
This question already has answers here:
How to get the key of a key/value JavaScript object
(20 answers)
Closed 2 years ago.
I want to convert an object like this:
let obj = {
arabicLang: false,
cancelVisitEmailAlert: false,
canselVisitSmsAlert: false
}
into an array of key-value pairs like this:
[
"arabicLang": false,
"cancelVisitEmailAlert": false,
"canselVisitSmsAlert": false
]
I read all questions in StackOverflow but none of them is my case
i try this but it return key and value in string:
let data = [];
for (const [key, value] of Object.entries(obj)) {
data.push(createData(key, value));
}
function createData(key, value) {
return key + ":" + value;
}
and also try this:
let arr = Array.of(obj)
console.log(arr)
/* output is
[{
arabicLang: false,
cancelVisitEmailAlert: false,
canselVisitSmsAlert: false
}]
*/
it keeps the object container
You can use .reduce or .map like:
let obj = {
arabicLang: false,
cancelVisitEmailAlert: false,
canselVisitSmsAlert: false
};
// Using .reduce
const result = Object.entries(obj).reduce((acc, [key, value]) => {
acc[key] ??= {[key]: value};
return acc;
}, {});
console.log(Object.values(result));
// Using .map
const result2 = Object.entries(obj).map(([key, value]) => ({[key]: value}));
console.log(result2);
Only thing instead of createData method, just use object literal to simplify.
let obj = {
arabicLang: false,
cancelVisitEmailAlert: false,
canselVisitSmsAlert: false,
};
let data = [];
for (const [key, value] of Object.entries(obj)) {
data.push({ [key]: value });
}
console.log(data);
This question already has answers here:
How to skip over an element in .map()?
(18 answers)
Closed 2 years ago.
If I have an object, such as,
const obj = {
a: 1,
b: 2,
c: 3,
}
I can map the keys and values as,
Object.entries(obj).map(([key, value]) => console.log(`${key}: ${value}`))
Is it possible in Javascript to omit a property, when mapping it?
Something like,
Object.entries({a: obj.a, ...obj}).map(([key, value]) => console.log(`${key}: ${value}`))
I can do the following:
Object.entries(obj).map(([key, value]) => key !== 'a' && console.log(`${key}: ${value}`))
But I feel like there can be a cleaner way to do this, and also this wouldn't work, because that mapped index will contain undefined. Just looking to clarify this.
you can use filter
Object.entries(obj).filter(([key, _]) => key !== "a").map();
Here is what you want:
const obj = {
a: 1,
b: 2,
c: 3,
}
const res = Object.entries(obj).filter(([key, value]) => key !== 'a');
console.log(res);
If you want to hide/exclude a key when using a map you can set its enumerable property to false, using Object.defineProperty:
const obj = {
a: 1,
b: 2,
c: 3,
}
// this will hide key 'b' from obj
Object.defineProperty(obj, 'b', {
enumerable: false,
});
Object.entries(obj).map(([key, value]) => console.log(`${key}: ${value}`))
This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Convert Javascript array of objects into one object
(4 answers)
How to convert array of objects in one specific object?
(9 answers)
shortest way to create a comma separated object list [duplicate]
(2 answers)
Closed 2 years ago.
I have data that looks like this.
[
{
key: 'myKey'
value: 'myValue'
},
{
key: 'mySecondKey'
value: 'mySecondValue'
},
{
key: 'myThirdKey'
value: 'myThirdValue'
},
]
The amount of objects varies depending on how much values an account has set. I'm trying to return this in a format that looks like this
{
mykey: 'myValue'
mySecondKey: 'mySecondValue'
myThirdkey: 'myThirdValue'
}
Any advice on how I would go about doing this?
You can do something, like
const src = [{key:'myKey',value:'myValue'},{key:'mySecondKey',value:'mySecondValue'},{key:'myThirdKey',value:'myThirdValue'},],
result = Object.assign({}, ...src.map(o => ({[o.key]: o.value})))
console.log(result)
.as-console-wrapper{min-height:100%;}
You can use reduce for this:
const data = [{key:"myKey",value:"myValue"},{key:"mySecondKey",value:"mySecondValue"},{key:"myThirdKey",value:"myThirdValue"}];
const res = data.reduce((obj, {key, value}) => ({...obj, [key]: value}), {});
console.log(res);
Other answers work but I feel like they are a bit complicated, here's a simple for of loop:
const data = [
{
key: 'myKey',
value: 'myValue'
},
{
key: 'mySecondKey',
value: 'mySecondValue'
},
{
key: 'myThirdKey',
value: 'myThirdValue'
}
];
const result = {};
for(const {key, value} of data) {
result[key] = value;
}
console.log(result);
This question already has answers here:
Why are Objects not Iterable in JavaScript?
(7 answers)
Closed 3 years ago.
data: [],
...
I load data from API call into data array. Then I try to arrange the data array into a map which can consist of a key, value pairs (value can be itself array) using below.
const dataMap = {};
for (let i = 0; i < data.length; i+=1) {
const key = data[i].product.name;
const value = data[i];
if (key in dataMap) {
dataMap[key].push(value);
} else {
dataMap[key] = [value];
}
}
But when I do the following I get the following error. What I am doing wrong?
{[...dataMap].map(([key, value]) => {}
Invalid attempt to spread non-iterable instance
This is my dataMap
DataMap is correctly calculate but when i iterate using the following code
Object.entries(dataMap).map((key, value) => {
console.log(key);
console.log(value)
})
it prints out the following. Value is some index which i dont understand why ? Value should be an array. My dataMap is a key, value (value is an array)
Your problem has nothing to do with react/react-native, its plain javascript:
dataMap is already an object, so you only can spread its entries.
// An empty object assign.
const dataMap = {};
// Shallow copy
const objShallowCopy = {...dataMap};
Also, you can rewrite your for-loops using reduce():
const dataSource = [
{ product: { name: 1 }, value: 10 },
{ product: { name: 1 }, value: 100 },
{ product: { name: 2 }, value: 30 },
{ product: { name: 2 }, value: 20 }
];
const dataMap = dataSource.reduce((acc, curr) => {
const prodArr = acc[curr.product.name];
return { ...acc, [curr.product.name]: prodArr ? [...prodArr, curr] : [curr] };
}, {});
console.log(dataMap);
Moreover, Object.entries returns an entries array so you need to fix your loggings:
// Bug
Object.entries(dataMap).map((key, value) => {
console.log(key);
console.log(value);
});
// Good
Object.entries(dataMap).map((([key, value]), index) => {
console.log("key", key);
console.log("value", value);
console.log("index", index);
});
dataMap is object, not an array. You cannot do [...dataMap].
You can convert dataMap to arrays of keys with Object.keys(dataMap) or to array of values with Object.values(dataMap)
So erroneous line should look like
Object.keys(dataMap).map(key => /* dataMap[key] will be value */)