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 }}), {})
Related
This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 1 year ago.
I have an array like :
export const switches = [
{ id: 1, switchName: 'HS - 3015', operation: 'Auto Start GA-3001 S', isActive: true },
{ id: 2, switchName: 'HS - 3016', operation: 'FSLL - 3001 (Pass - 1)', isActive: false },
{ id: 3, switchName: 'HS - 3017', operation: 'FSLL - 3002 (Pass - 2)', isActive: true }
];
In my component I added a additional property value which is boolean and which is used for control switch.
In a function I first duplicate this array and than modify this duplicate array that is value: true/false to value: 'normal/bypass'. The big issue is I am not getting my original array. I am always get the modified array.
What is the problem, I can't figure out.
Switch change and Submit function like this:
const onSwitchChange = (e, switchId) => {
const { checked } = e.target;
const oldState = [...state];
const updatedState = oldState.map(s => {
if (s.id === switchId) {
s['value'] = checked;
}
return s;
});
setState(updatedState);
};
const onSubmit = () => {
const oldData = [...state];
const data = oldData.map(item => {
item.value = item.value === true ? 'Bypass' : 'Normal';
return item;
});
document.getElementById('jsonData').textContent = JSON.stringify(data, null, 2);
};
Find in codesandbox: https://codesandbox.io/s/switch-control-4ovyk
the map function will always return a new array with elements that are the result of a callback function.
In your case, the map function should return a new array with the value changed to Bypass or Normal and it will be stored in the constant data.
However, you can still access your original array by calling oldData
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 }
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:
JavaScript "cannot read property "bar" of undefined [duplicate]
(4 answers)
Closed 4 years ago.
I'm trying to change JSON structure for push to my database
my old JSON :
[
{"name": "nameGallery"},
{"img": "1.jpg"},
{"img": "2.img"}
]
And I want to group "img" variable to "Images" Array like this:
[
{
"name": "nameGallery",
"Images": [
{"img": "1.jpg"},
{"img": "2.img"}
]
}
]
I'm trying to use object.assign to manage it but I don't know why it error.
function getData() {
fetch('text/upload.json').then((res) => res.json())
.then((data) => {
console.log(data);
data = data.map(o => Object.assign({}, o,
{ Images: o.Images.map(({ img }) => ({ img: img })) }
));
})
}
My Result:
In your solution you are calling .map which will create you one array entry for every array entry in your initial data.
As you described, you expect one object as a result and not an array of object. So look at the following :
const data = [{
name: 'nameGallery',
},
{
img: '1.jpg',
},
{
img: '2.img',
},
];
// You want to create a new object using all the others objects
const ret = data.reduce((tmp, x) => {
// If the key below is 'img', we push the object into 'Images'
// void 0 means undefined
if (x.img !== void 0) {
tmp.Images.push(x);
return tmp;
}
// If the key is not 'img'
// We copy the keys into tmp
return {
...tmp,
...x,
};
}, {
// initialize 'Images' key here it won't be undefined
// when pushing the first data
Images: [],
});
console.log(ret);
You can try something like this:
function getData() {
fetch('text/upload.json').then((res) => res.json())
.then((data) => {
const name = data.find(o => !!o.name);
return {
name: name.name,
Images: data.filter(o => !!o.img)
};
})
}
This question already has answers here:
Creating object with dynamic keys [duplicate]
(2 answers)
Closed 5 years ago.
const cars = [
{
'id': 'truck',
'defaultCategory': 'vehicle'
}
]
const output = []
Object.keys(cars).map((car) => {
output.push({
foo: cars[car].defaultCategory
})
})
console.log(output)
This work fine, however what I want to achieve is so that the newly crated object has structure of 'truck': 'vehicle'.
So if I replace push argument with
${cars[car].id}`: cars[car].defaultCategory
I get SyntaxError: Unexpected template string
What am I doing wrong?
Use map on the array, and not the keys (the indexes) to get an array of objects. For each object use computed property names to set the id value as the key:
const cars = [
{
'id': 'truck',
'defaultCategory': 'vehicle'
}
];
const result = cars.map(({ id, defaultCategory }) => ({ [id]: defaultCategory }));
console.log(result);
You should use .map() over your cars array and not Object.keys(cars):, we don't use Object.keys() with arrays.
This is how should be your code:
var output = cars.map(function(car) {
return {
[car.id]: car.defaultCategory
};
});
var cars = [{
'id': 'truck',
'defaultCategory': 'vehicle'
}];
var output = cars.map(function(car) {
return {
[car.id]: car.defaultCategory
};
});
console.log(output);