I want to convert an object into an array of object but my code give the wrong result like shown below..
// object
data = { user_id : '123' }
// expected result
data = [ { user_id : '123' } ]
// what I get instead
data = [ { v : '123' } ]
my code:
let arr = [];
Object.keys(data).map(v => {
console.log(v, data[v]); // here it shows 'user_id' and '123' as it's supposed to
arr.push({ v:data[v] }); // but here it uses the 'v' as property instead of 'user_id'
});
You need to put v inside a square bracket
const data = {
user_id: '123'
}
let arr = [];
Object.keys(data).map(v => {
arr.push({
[v]: data[v]
});
});
console.log(arr)
Alternatively you can also use Object.entries. You dont need initialize let arr = []; as map will create a new array
const data = {
user_id: '123'
}
const arr = Object.entries(data).map(v => {
return {
[v[0]]: v[1]
}
});
console.log(arr)
when you need to use variable as key in object, you must use [].
Example:
const key = 'user_id'
const obj = {
[key]: 'user'
}
## result
{
'user_id': 'user
}
So change v to [v].
let arr = [];
Object.keys(data).map(v => {
arr.push({ [v]:data[v] }); // replace v to [v]
});
Related
I am trying to extract id from the below array of objects and so far I am able to give it a go with the below code but it is showing undefined and cannot get id , would you please check the code and adjust to get id out?
const array = [{
contact: {
id: 1,
email: 'roar#gmail.com',
},
date: '2/4/22'
},
{
contact: {
id: 2,
email: 'grr#gmail.com',
},
date: '2/4/22'
}
]
function extractValue(arr, prop) {
let extractedValue = [];
for (let i = 0; i < arr.length; ++i) {
// extract value from property
extractedValue.push(arr[i][prop]);
}
return extractedValue;
}
const result = extractValue(array, 'contact.id');
console.log(result);
A good way to do this is the Array Map method
This will get all the id's from your array
const result = array.map((val) => val.contact.id)
const extractValue = (array, path) => {
const [first, second] = path.split('.')
if (second) return array.map(obj => obj[first][second])
return array.map(obj => obj[first])
}
const res = extractValue(array, 'contact.id')
console.log(res)
// => [ 1, 2 ]
this will support single and double level nested results
function find(val, arr) {
for (let x of arr)
val = val[x];
return val;
}
function extractValue(arr, prop) {
return array.map(x => find(x, prop.split(".")))
}
I have a problem to make an array of strings into objects of url paths (for breadcrumbs)
I have this array :
const array = ['visit', 'schedule', 'validator']
What I tried :
const routeArray = array.map((b) => ({
label: b,
route: `/${b}`,
}))
console.log(routeArray)
result :
[
{label: "visit", route: "/visit"},
{label: "schedule", route: "/schedule"},
{label: "validator", route: "/validator"},
]
what I want to achieve :
[
{label: "visit", route: "/visit"},
{label: "schedule", route: "/visit/schedule"},
{label: "validator", route: "/visit/schedule/validator"}
]
Any help ?
Just concatenate the String while going through the array:
const array = ['visit', 'schedule', 'validator'];
let route = "";
const result = array.map(label => {
route += '/' + label;
return { label, route };
});
Array.prototype.map(), Array.prototype.slice() and Array.prototype.join() can be your best friends, here:
const input = ['visit', 'schedule', 'validator'];
const output = input.map((item, index) => {
return {
label: item,
route: '/' + input.slice(0, index + 1).join('/')
}
});
// test
console.log(output);
Please check this out and let me know if this is what you were looking for:
const array = ['visit', 'schedule', 'validator']
const newArray = array.map((entry, index) => {
const route = [];
for (let i = 0; i < index + 1; i++) {
route.push(array[i]);
}
return {
label: entry,
route: route.join('/'),
};
});
console.log(newArray);
In this approach, I loop through as many elements as the order of the current element of array, pushing them into the route array. When creating the object properties, I join the elements of route separated by '/'.
Here is how we can do this using the reduce method:
const arr = ["visit", "schedule", "validator"];
const res = arr.reduce((acc, curr, idx, self) => {
// Our route property of our needed data structure
const route = `/${self.slice(0, idx)}${idx > 0 ? "/" + curr : curr}`;
// Our new object
const obj = { label: curr, route };
return [...acc, obj];
}, []);
console.log(res);
Can be done using a for loop. You need to have a variable which tracks your incrementing route and persists over loop iterations.
const array = ['visit', 'schedule', 'validator'];
let ansArray = [];
let incrVal = '';
for(let i = 0 ; i < array.length; i++){
let ans = incrVal + '/' + array[i];
ansArray.push({'label' : array[i], 'route' : ans});
incrVal = ans;
}
console.log(ansArray);
const array = ['visit', 'schedule', 'validator'];
const results = array.map((item, index, arr) => {
return {
label: item,
route: '/' + arr.slice(0, index + 1).join('/'),
};
});
console.log(results);
Using reduce array method
const array = ["visit", "schedule", "validator"];
const res = array.reduce((acc, curr, idx, arr) => {
acc.push({
label: curr,
route:'/'+ arr.slice(0, idx + 1).join('/')
})
return acc;
}, []);
console.log(res);
I think this is the shortest way to do this:
const input = ["visit", "schedule", "validator"];
const res = input.map((label, i, arr) => ({
label,
route: '/' + arr.slice(0, i + 1).join("/")
}));
console.log(input);
console.log(res);
I'm trying to build an object given an array of objects
const someArray = [
{
name: 'x.y',
value: 'Something for Y'
},
{
name: 'x.a.z',
value: 'Something for Z'
}
]
to look like this
{
x: {
a: {
z: 'Something for Z'
},
y: 'Something for Y'
}
}
I have this code
const buildObj = data => {
let obj = {}
data.forEach(item => {
let items = item.name.split('.')
items.reduce((acc, val, idx) => {
acc[val] = (idx === items.length - 1) ? item.value : {}
return acc[val]
}, obj)
})
return obj
}
buildObj(someArray)
but it doesn't include the y keypair. what's missing?
What you want to do is create an object, then for each dotted path, navigate through the object, creating new object properties as you go for missing parts, then assign the value to the inner-most property.
const someArray = [{"name":"x.y","value":"Something for Y"},{"name":"x.a.z","value":"Something for Z"}]
const t1 = performance.now()
const obj = someArray.reduce((o, { name, value }) => {
// create a path array
const path = name.split(".")
// extract the inner-most object property name
const prop = path.pop()
// find or create the inner-most object
const inner = path.reduce((i, segment) => {
// if the segment property doesn't exist or is not an object,
// create it
if (typeof i[segment] !== "object") {
i[segment] = {}
}
return i[segment]
}, o)
// assign the value
inner[prop] = value
return o
}, {})
const t2 = performance.now()
console.info(obj)
console.log(`Operation took ${t2 - t1}ms`)
.as-console-wrapper { max-height: 100% !important; }
This is ABD at this point but I did it with a recursive builder of the path.
const someArray = [
{
name: 'x.y',
value: 'Something for Y'
},
{
name: 'x.a.z',
value: 'Something for Z'
}
]
const createPath = (path, value) => {
if(path.length === 1){
let obj = {}
obj[path.shift()] = value
return obj
}
let key = path.shift();
let outObject = {}
outObject[key] = { ...createPath(path, value) }
return outObject
}
const createObjectBasedOnDotNotation = (arr) => {
let outObject = {}
for(let objKey in arr){
const { name, value } = arr[objKey];
let object = createPath(name.split("."), value)
let mainKey = Object.keys(object)[0];
!outObject[mainKey] ?
outObject[mainKey] = {...object[mainKey]} :
outObject[mainKey] = {
...outObject[mainKey],
...object[mainKey]
}
}
return outObject
}
console.log(createObjectBasedOnDotNotation(someArray))
Here's an option using for loops and checking nesting from the top down.
const someArray = [
{
name: 'x.y',
value: 'Something for Y'
},
{
name: 'x.a.z',
value: 'Something for Z'
}
]
function parseArr(arr) {
const output = {};
for (let i = 0; i < arr.length; i++) {
const {name, value} = arr[i];
const keys = name.split('.');
let parent = output;
for (let j = 0; j < keys.length; j++) {
const key = keys[j];
if (!parent.hasOwnProperty(key)) {
parent[key] = j === keys.length - 1 ? value : {};
}
parent = parent[key];
}
}
return output;
}
console.log(parseArr(someArray));
I have a json object with objects inside of it
such as user: {"name": "tim"} and would like a way to turn that in "user.name": 'tim'
I've tried: Javascript Recursion normalize JSON data
Which does not return the result I want, also tried some packages, no luck
You can use a recursive approach to flatten nested objects, by concatenating their keys, as shown below:
const flattenObject = (obj) => {
const flatObject = {};
Object.keys(obj).forEach((key) => {
const value = obj[key];
if (typeof value === 'object') {
const flatNestedObject = flattenObject(value);
Object.keys(flatNestedObject).forEach((nestedKey) => {
flatObject[`${key}.${nestedKey}`] = flatNestedObject[nestedKey];
});
} else {
flatObject[key] = value;
}
});
return flatObject;
};
const obj = {
user: { name: 'tim' },
};
console.log(flattenObject(obj));
This solution works for any amount of levels.
If your environment does not support Object.keys, you can use for..in instead:
const flattenObject = (obj) => {
const flatObject = {};
for (const key in obj) {
if (!obj.hasOwnProperty(key)) continue;
const value = obj[key];
if (typeof value === 'object') {
const flatNestedObject = flattenObject(value);
for (const nestedKey in flatNestedObject) {
if (!flatNestedObject.hasOwnProperty(nestedKey)) continue;
flatObject[`${key}.${nestedKey}`] = flatNestedObject[nestedKey];
}
} else {
flatObject[key] = value;
}
}
return flatObject;
};
const obj = {
user: { name: 'tim' },
};
console.log(flattenObject(obj));
This can easily be done like so:
const myObject = {
user: {
firstname: "john",
lastname: "doe"
}
}
function normalize(suppliedObject = {}) {
const newObject = {};
for (const key of Object.keys(suppliedObject)) {
for (const subKey of Object.keys(suppliedObject[key])) {
newObject[`${key}.${subKey}`] = suppliedObject[key][subKey];
}
}
return newObject;
}
console.log(normalize(myObject));
Be aware that this only normalizes 1 level deep. You can extend the function to normalize all the way down to the last level.
I want to rewrite an array and to get a new one at the final.
This is my code:
const arr = [
{
type:"Fiat", model:"500", color:"white"
},
{
type:"ford", model:"5300", color:"gray"
}
];
const newArr = arr.map(i => {
const r = {
...arr,
power:2
}
return r
})
console.log(newArr)
Now i get the wrong result, because one every iteration, the new array grow with a copy of the first array:
const r = {
...arr,
power:2
}
How to get the next result?
{
type:"Fiat", model:"500", color:"white", power: 2
},
{
type:"ford", model:"5300", color:"gray", power: 2
}
You are spreading arr .You need to spread i which is the object inside the array.
const arr = [
{
type:"Fiat", model:"500", color:"white"
},
{
type:"ford", model:"5300", color:"gray"
}
];
const newArr = arr.map(i => {
const r = {
...i,
power:2
}
return r;
})
console.log(newArr)
With array function you can implicitly
const arr = [
{
type:"Fiat", model:"500", color:"white"
},
{
type:"ford", model:"5300", color:"gray"
}
];
const newArr = arr.map(i => ({...i, power: 2}));
console.log(newArr)
You need to spread the current object that you are getting as:
const newArr = arr.map(i => ({ ...i, power: 2 }));
You want to do this, you are spreading arr and should be spreading the array getting passed to map (e.g. i):
const newArr = arr.map(i => {
const r = {
...i,
power:2
}
return r
})