Assign Keys when converting array to json - Node JS [duplicate] - javascript

This question already has answers here:
Javascript - convert array of arrays into array of objects with prefilled values
(4 answers)
Closed 2 years ago.
I Have some array like below:
[
[
'James',
23,
'male'
],
[
'Britney',
45,
'female'
]
]
I would like to turn that into a json looking like:
[
{
'name': 'James',
'age': 23,
'gender'': 'male'
},
{
'name': 'Britney',
'age': 45,
'gender'': 'female'
}
]
I understand the json stringify part to convert the array to json but not sure how to create the keys for the values in an efficient way. Any help is greatly appreciated.

Use map, then destruct the array and return an object.
const arr = [
[
'James',
23,
'male'
],
[
'Britney',
45,
'female'
]
]
const res = arr.map(([name, age, gender]) => ({
name,
age,
gender
}))
console.log(res);

You can do this with map with proper destructuring(for shortcut):
var a=[ [ 'James', 23, 'male' ], [ 'Britney',45,'female']];
var result = a.map(([name,age,gender])=>({name, age, gender}));
console.log(result);

Related

JS create new array from certain item

I have 2 dimensional array myArray:
[
[ '567576', 'John', 'Doe' ],
[ '098897', 'John', 'Doe' ],
[ '543539', 'John', 'Doe' ],
[ '234235', 'John', 'Doe' ],
[ '345348', 'John', 'Doe' ],
[ '432574', 'John', 'Doe' ]
]
Is it possible to create a new array from myArray starting from a certain first value?
For example create a new array starting from id 543539. Anything above the array containing 543539 will not be added.
You can make use of findIndex() which returns the index of the first item that matches the condition.
Combine it with slice() to cut your array at the specific position:
const myArray = [
['567576', 'John', 'Doe'],
['098897', 'John', 'Doe'],
['543539', 'John', 'Doe'],
['234235', 'John', 'Doe'],
['345348', 'John', 'Doe'],
['432574', 'John', 'Doe']
]
console.log(myArray.slice(myArray.findIndex(item => item[0] === "543539")));
Sure, assuming all the internal arrays are structured the same way, you can do something like let newArray = myArray.filter(innerArray => Number(innerArray[0]) > 543539)
Edit: This is assuming you want all subarrays where the first item is a number larger than 54539, as opposed to finding all of the subarrays that physically follow the first occurrence of a subarray with 54539 as the first value
Yes, that is possible and straightforward process.
You can use the javascript map method which returns a new array
newArray = myArray.map(item=> item[0])

Accessing duplicates in objects in the same array?

I have an array with multiple objects
arr = [
{name: 'xyz',
age: 13,
},
{name: 'abc',
age: 15,
},
{name: 'abc',
age: 15,
}]
how do I find the duplicate in this array and remove the object that is duplicated in the array? They are all in one array.
Apologies. I just realized what I am trying to do is, remove the object entirely if there's a duplicate in one key... so if the age is similar, I will remove object name "def". Is this possible?
arr = [
{name: 'xyz',
entry: 1,
age: 13,
},
{name: 'abc',
entry: 2,
age: 15,
},
{name: 'def',
age: 13,
entry: 3
}]
You could achieve this by the following steps:
transform each element into an object that is key-sorted, this will make objects consistent in terms of key-value pairs order, which will help us in the next step
map the array into JSON-stringified value, and store it into a Set(), which would help us store only unique stringified objects
turn the Set() back into array
map the array back into objects by JSON.parse() each element
const arr = [
{ name: "xyz", age: 13 },
{ age: 15, name: "abc" },
{ name: "abc", age: 15 },
]
const sortKeys = obj =>
Object.fromEntries(
Object.entries(obj).sort((keyValuePairA, keyValuePairB) =>
keyValuePairA[0].localeCompare(keyValuePairB[0])
)
)
const res = Array.from(
arr
.map(sortKeys)
.map(el => JSON.stringify(el))
.reduce((set, el) => set.add(el), new Set())
).map(el => JSON.parse(el))
console.log(res)
References
Set
Object.entries()
Object.fromEntries()

need to convert object into array

const obj = {
obj1: [{
name: 'Max',
age: 25
}]
}
Object.values(obj).map(obj => console.log(obj.obj1.name))
Uncaught TypeError: Cannot read property 'name' of undefined. I need to get that name
If you are just trying to loop through the object values, using forEach instead of the map is a good idea. Map returns a new array but forEach doesn't. Also, Object.values() will return an array of all the values in the object(each value is an array of objects in this case). Therefore, using 2 forEach loops makes the task easier.
const obj = {
obj1: [{
name: 'Max',
age: 25
}],
obj2: [{
name: 'Min',
age: 26
}]
}
Object.values(obj).forEach(mainObj => mainObj.forEach(obj => console.log(obj.name )))
You are trying to access the wrong key. Your object has a key obj1 which is an array. You have to loop through that array as well.
const obj = {
obj1: [{
name: 'Max',
age: 25
}],
obj2: [{
name: 'Min',
age: 24
}]
}
var objectValuesArr = Object.values(obj)
var particularObj = objectValuesArr.map(obj => obj.forEach(obj => console.log(obj.name)))

how to extract array type in an array object in javascript [duplicate]

This question already has answers here:
Flatten Javascript array
(5 answers)
How to get items inside nested arrays [duplicate]
(2 answers)
Closed 3 years ago.
How can i filter the name, only keep the array type in an newArray?
let data = [
{name: 'Andy', details: [{age: 20, sex: "male"}]},
{name: 'John', details: [{age: 25, sex: "male"}]},
];
//Output result
let newArray = [{age:20, sex: "male"}, {age:25, sex: "male"}];
I try to complete the details.. how it can help. =)
you can use reduce like this:
let result = data.reduce((acc, curr) => [...acc, ...curr.details],[])
I don't quite understand your question. Try to use ES5 map method:
let data = [
{name: 'Andy', details: [{age: 20, sex: male}]},
{name: 'John', details: [{age: 25, sex: male}]},
];
let newArray = data.map(value=> value.details[0])
// newArray is [{age: 20, sex: male}, {age: 25, sex: male}]

How to take an array of objects and create arrays based on property values?

I have an array of objects and trying to take thevalues inside those objects and push them into an array based on the same property value. So for example.
array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
]
I have this array of objects and now I want to iterate through it and create arrays with all name values and age values. The array also needs to be the same name as the values. So the result will be.
name = ['John', 'Lily']
age = [12, 22]
How would I be able to do this?
Just map over the array like so:
const array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
]
const name = array.map(e => e.name);
const age = array.map(e => e.age);
console.log(name);
console.log(age);
EDIT
If the array has dynamic objects, you can do this:
const array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
];
for (var key in array[0]) {
window[key] = array.map(e => e[key]);
}
console.log(name);
console.log(age);

Categories