This question already has an answer here:
Dynamic object property names?
(1 answer)
Closed 1 year ago.
Going over this code in github https://github.com/WebDevSimplified/postman-clone, I simply do not understand below portion
function keyValuePairsToObjects(container) {
const pairs = container.querySelectorAll('[data-key-value-pair]')
return [...pairs].reduce((data, pair) => {
const key = pair.querySelector('[data-key]').value
const value = pair.querySelector('[data-value]').value
if (key === '') return data
return { ...data, [key]: value }
}, {})
}
{...data, [key]: value} Why is key inside of an array?
Key is not an array, this is the syntax for using a variable name as the key, like the obj["prop"] syntax, { ["prop"]: true } is like { prop: true }.
Context for comments:
> { ["prop"]: true }
{ prop: true }
> { prop: true }
{ prop: true }
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 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:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 2 years ago.
case 'ADD_CHAT_MESSAGE':
const index = state.tasks.findIndex(elm => elm.userid === action.taskid)
const task = state.tasks
return update(
state, { tasks: { index: { $set: action.task } } })
I would like to use index inside update function but my IDE alerting me that index is declared nut never used.
Since index is dynamic, you must use [] with it, otherwise it will just be setting the index key
case 'ADD_CHAT_MESSAGE':
const index = state.tasks.findIndex(elm => elm.userid === action.taskid)
const task = state.tasks
return update(
state, { tasks: { [index]: { $set: action.task } } })
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 */)
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 3 years ago.
I have object like picture below.
I want to use map() to retrieve the object like
{
"2643216":{pg:1,pt:1},
"1304681":{pg:1,pt:1}
}
Here is my code.
Object.keys(obj).map(function(x){
return {obj[x].number:{'pg':obj[x].pg,'pt':obj[x].pt}}
})
But errors may appear at the obj[x].number.
The debug errors notifies me the ignorance of the : (colon).
Is there mistake I make and any adjustment you can suggest-
or other way can retrieve the object I want?
Thank you.
this should do the job:
function groupByNumber(data) {
return Object
.keys(data)
.reduce(function(result, key) {
var value = data[key];
result[value.number] = { pt: value.pt, pg: value.pg };
return result;
}, {});
};
var data = {
'LKB_something': { number: 1, pg: 1, pt: 5 },
'LKB_something_else': { number: 2, pg: 1, pt: 5 },
'LKB_something_else_1': { number: 3, pg: 1, pt: 5 },
};
console.log('result', groupByNumber(data));
// ES-NEXT would let you be more coincise
const groupByNumber = data => Object.values(data).reduce(
(result, { number, ...rest }) => ({ ...result, [number]: rest }),
{},
);
For a dynamic key in a JavaScript object, you need square brackets to make a computed property name:
return { [obj[x].number]: { "pg": obj[x].pg, "pt": obj[x].pt }}
And your code could be simplified using Object.values and the implicit return of an arrow function, along with destructuring and shorthand property notation, like so:
Object.values(obj).map(({ number, pg, pt }) => ({ [number]: { pg, pt }}))
Note that the above returns an array of objects - if you want an object:
Object.values(obj).reduce((a, { number, pg, pt }) => ({ ...a, [number]: { pg, pt }}), {})