Constructing raw data out of array in javascript [duplicate] - javascript

This question already has answers here:
Convert Array to Object
(46 answers)
Closed 12 months ago.
I need to construct API body for using in javascript fetch. The length of array is twenty or so and I need a loop.
I have an array of objects:
[
{
name:"x",lname:"y"
},
{
name:"x2",lname:"y2"
},
]
and this what I want to achieve:
{
"0":{
"name":"x",
"lname":"y"
},
"1":{
"name":"x2",
"lname":"y2"
},
}
This is raw in postman body:
Any guide and help would be appreciated.

Converting an Array to an Object is easily done with Array.reduce and using the index argument as the key of the properties:
const data = [
{name:"x",lname:"y"},
{name:"x2",lname:"y2"},
]
console.log(
data.reduce((acc, item, i) => ({...acc, [i]:item}) ,{})
)
Or shorter, as suggested by #CherryDT (in the comments below), which automatically converts the Array to an Object consisting of keys derived from the array's items' indices:
const data = [
{name:"x",lname:"y"},
{name:"x2",lname:"y2"},
]
console.log({...data})
Tip: If you want the keys indices to start from 1 and not 0, do:
console.log({...[,...data]})

Related

Looping through an object without using Object.entries() on each key of the inner object [duplicate]

This question already has answers here:
How to loop through a plain JavaScript object with the objects as members
(28 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 months ago.
I would like to know how to loop through a nested object without specifying keys. I mean just to take the name of the object to do the loop. Is there any method to achieve it?
You can see at the bottom what I tried. It actually works, but I want to know if there is a way to do this without mentioning the keys(hero, monster)
Object to loop through:
const characterData = {
hero: {
name: "Wizard",
avatar: "images/wizard.png",
health: 60,
diceCount: 3,
currentDiceScore: []
},
monster: {
name: "Orc",
avatar: "images/orc.png",
health: 10,
diceCount: 1,
currentDiceScore: []
},
};
Object.entries(characterData.hero).forEach(([key, value]) => {
console.log(`${key}: ${value}`)
});
You can first iterate over Object.values() which, in this case, are the nested objects hero, monster and so on.. using Array.prototype.forEach(), and then your code that iterates over Object.entries() again using Array.prototype.forEach()
But notice that in the callbackFn function is used the square brackets Destructuring assignment and inside the console.log() Template literals (Template strings):
const characterData = {hero: {name: "Wizard",avatar: "images/wizard.png",health: 60,diceCount: 3,currentDiceScore: []},monster: {name: "Orc",avatar: "images/orc.png",health: 10,diceCount: 1,currentDiceScore: []},}
Object.values(characterData)
.forEach(o =>
Object.entries(o)
.forEach(([k, v]) =>
console.log(`${k}: ${v}`)))

How to create array of objects from array: javascript [duplicate]

This question already has answers here:
How to convert array of items to array of objects?
(2 answers)
Closed 1 year ago.
I am trying to convert an array of elements to an array of objects in Javascript (react)
Here is the data I am getting from my API
"versions": [
"1.0.1.2",
"1.0.22.0",
"1.1.0.12",
"2.5.2.6",
"2.5.2.7",
"2.7.5.11",
"2.7.7.7",
"3.9.2.94",
"3.9.3",
"5.2.0.87",
"9.5.0.210" ]
And I am trying to convert to an array of object which should look like this
options = [
{ value: "1.0.1.2", label: "1.0.1.2" },
{ value: "1.0.22.0", label: "1.0.22.0" },
{ value: "2.5.2.6", label: "2.5.2.6" },
];
I tried using the map function
versions = VersionloginData.data.versions.map((version) => [version.value, version.label])
But didn't work out well , i am getting undefined as value objects
You needed to return an object inside the map callback:
versions = VersionloginData.data.versions.map((version) => ({ value: version, label: version }))
Its should be.
const data = {
"versions": [
"1.0.1.2",
"1.0.22.0",
"1.1.0.12",
"2.5.2.6",
"2.5.2.7",
"2.7.5.11",
"2.7.7.7",
"3.9.2.94",
"3.9.3",
"5.2.0.87",
"9.5.0.210"]
}
const output = data.versions.map(item => ({ value: item, label: item }));
console.log(output);
Why your code is not working?
You are accessing incorrect nodes with [version.value, version.label]. value and label doesnot exist on version. Instead, you should return an object with keys value and label having same value.
you can try this
var options = []
versions.forEach((v)=>{
options.push({
value: v,
label: v,
})
})

How to update nested keys when you have keys in array javascript [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 1 year ago.
I have a requirement wherein I get nested object keys in an array. I have an array of keys like
let keys = ["vehicleInformation", "VehicleBlock|1", "DriverAssociation|1", "DriverInvolvedAssociation"]
There is already a JSON data that is stored in a variable and I have to update a data object.
data['vehicleInformation']['VehicleBlock'][1]['DriverAssociation'][1]['DriverInvolvedAssociation'] = value;
Is there a way to achieve this in javascript?
Initial value of data:
data = {};
Expected result:
data = {
vehicleInformation: {
VehicleBlock: [
{},
{
DriverAssociation: [
{},
{DriverInvolvedAssociation: value},
],
},
],
},
};
keys = ["vehicleInformation", "VehicleBlock|1", "DriverAssociation|1", "DriverInvolvedAssociation"]
data = {
vehicleInformation: {
VehicleBlock: [
0,
{
DriverAssociation: [
0,
{},
],
},
],
},
};
let value = 42;
let keysToLast = keys.flatMap(key => key.split("|"));
let lastKey = keysToLast.pop();
keysToLast.reduce((a, e) => a[e], data)[lastKey] = value;
console.log(data);
Array keys are just strings like object keys, no reason to treat them differently (thus flatMap). Then just reduce to find the object whose property you need to set, and set it.

Convert array to map [duplicate]

This question already has answers here:
How to convert an array of objects to object with key value pairs
(6 answers)
Closed 2 years ago.
I am trying to convert a array of unique ids to a flat map of theses
const arr = [ { user1: 'val' }, { user2: 'val' } ]
and I want to convert to
{ user1: 'val', user2: 'val' }
How can I do this?
Using array.reduce
arr.reduce((obj, val) => ({...obj, ...val}))

Upsert array value in NodeJS

I have a simple scenario where I am trying to update an array value that is part of an object, but the object does not seem to reflect the update.
Code:
var request =
{
description: 'my-desc',
details: []
};
request.details['shelf-info'] =
[
{
key: 'ShelfNumber',
value: '100'
}
];
console.log(JSON.stringify(request))
With the assignment of shelf-info, I would have expected the resulting output to be similar to:
Desired Output:
{ "description": "my-desc", "details": { "shelf-info": [ "key": "ShelfNumber", "value": "100" ] } }
but the update doesn't seem to have taken effect:
Actual Output:
{"description":"my-desc","details":[]}
I have found that I can add simple objects (strings) to an array using append, but shelf-info may or may not already be in the request.details section by the time this code gets executed...how would I handle both cases?
You want a plain object ({}) for details, not an array ([]).
When arrays are serialized to JSON, the JSON output only includes values that are stored in whole-number indices. Arrays may validly have other properties whose key names are not non-negative integers (such as the string shelf-info) but those properties are not included the JSON serialization of the array.
You're using an array as if it's an object, which it technically is, but that won't add anything to the array, and it won't convert the array to a regular object with key/value pairs.
Easy fix:
var request = {
description: 'my-desc',
details: { }
};
Also since it's 2020 you should be using let instead of var in most cases.
Try Below. Detail property should be an object.
var request =
{
description: 'my-desc',
details: {}
};
request.details['shelf-info'] =
[
{
key: 'ShelfNumber',
value: '100'
}
];
console.log(JSON.stringify(request))

Categories