Related
const datafromback=[[{name:ravi}],[{}],[{}],[{}]]
I want to access ravi. Can anyone help me how can i see ravi in my console.with dealing with nested arrays
I not getting approach but i can use map to map through datafromback array but don't know how to get inside it
You can use 0 index
const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]]
const dataFrom = (arr, nameRavi) => {
let result
arr.forEach((ele) => {
if (ele[0].name === nameRavi) result = ele[0].name
})
return result
}
console.log(dataFrom(datafromback, 'ravi'))
one possible way is to use flat first to remove nested array
const datafromback=[[{name:ravi}],[{}],[{}],[{}]]
const flatternArray = datafromback.flat() // [{name:ravi},{},{},{}]
flatternArray.map(item => {
console.log(item.name) //
})
you can do this :
const datafromback=[[{name:'ravi'}],[{}],[{}],[{}]]
const [{name}] = datafromback.find(data=>data.find(item=>item.name === 'ravi')?.name === 'ravi')
console.log(name)
You can create a recursive function if you have non-fixed dimensions array :
const handle = e => {
if (Array.isArray(e))
return e.map(handle)
else {
console.log(e.name)
}
}
handle(array)
Or if you know the dimensions, you can use nested for loops like so :
// example for 2 dimensions
for (let y = 0; y < array.length; y++)
for (let x = 0; x < array[y].length; x++)
console.log(array[y][x].name)
Hey so what you have above is a 2D object array. if you just want to console you can use a nested forEach to get the key value, like this.
datafromback.forEach(data => {
//this is the nested array that contains the objects
data.forEach(obj => {
//here you can access the actual object
if (obj?.name) console.log(obj.name);
});
});
this will return the value of key (name) if present ie ravi in your case.
you can do it like this
const datafromback = [[{ name: 'ravi' }], [{}], [{}], [{}]];
const names = [];
datafromback.map((items) => {
items.map((item) => {
if (item?.name) names.push(item?.name);
});
});
console.log(names);
Fairly new to JSON and I'm trying to get my head around conversions. I have an array:
['Role1', 'Role2', 'Role3']
and I'm trying to stringify it so that it reads as
{"Role1": true, "Role2": true, "Role3": true}
So far I've tried assigning the original array to an object and the calling stringify but I can't figure out how to add the boolean value in the string. Thanks in advance.
You'll have to create an intermediate reduce function to assign those values before converting to JSON.
const data = ['Role1', 'Role2', 'Role3']
const makeJson = () =>
JSON.stringify(data.reduce((a, c) => ({ ...a, [c]: true }), {}))
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Is this what you need as output?
const arr = ['Role1', 'Role2', 'Role3']
const result = JSON.stringify(arr.reduce((a, n)=>{
return {
...a,
[n]: new Boolean(true).toString()
}
},{}))
console.log(result)
Another approach could be to combine Object.fromEntries with Array.prototype.map
const data = ['Role1', 'Role2', 'Role3']
const result = Object.fromEntries(data.map(s => [s, true]));
console.log(JSON.stringify(result));
This should do the trick:
let rolesArray = ['Role1', 'Role2', 'Role3'];
let rolesObject = {};
// iterate over roles to fill an object
rolesArray.forEach((role) => {
rolesObject[role] = true;
});
JSON.stringify(rolesObject) // Outputs the desired string
Or in a more concise way but less readable for a SO example :
JSON.stringify(rolesArray.reduce((o, s) => { o[s] = true; return o }, {}));
I have a preference for using the for-loop — still valid but other methods will be much short.
var array = ["Role1", "Role2", "Role3"],
json = {};
for (i = 0; i < array.length; i++) {
json[array[i]] = true;
}
console.log(json);
Use reduce() so we can set the value to true without a second loop
Using the spread operator (...) to merge the objects
const data = ['Role1', 'Role2', 'Role3'];
const obj = data.reduce((prev, cur) => ({ ...prev, [cur]: true }), {});
console.log(obj);
console.log(JSON.stringify(obj));
{
"Role1": true,
"Role2": true,
"Role3": true
}
{"Role1":true,"Role2":true,"Role3":true}
if you want to do that you must use code Below .
json-encode(Array)
I have sample JSON in form of
var sample=[{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}]
var result = [];
sample.forEach(function(e){
let obj = {}
obj.id=e.id
obj['somekey']=e.children[0].value
obj['someanotherkey']=e.children[1].type
result.push(obj);
})
console.log(result)
How do i can achieve same using map es-6
var sample=[{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}]
var output = sample.map(({ id, children }) => ({ id, ...children[0] }));
console.log(output);
.map() returns an array, so you must set up a variable to hold that result. Then, within the loop, you use return to effectively push items into the array.
var sample=[{"id":200,"children":[{"value":300,"type":"SINGLE"},{"value":400,"type":"CLASSIC"},{"value":600,"type":"DUAL"}]},{"id":300,"children":[{"value":500,"type":"TRIO"},{"value":600,"type":"MUSICAL"},{"value":700,"type":"UMBRELA"}]}];
let result = sample.map(function(e){
let obj = {}
obj.id=e.id;
obj['value']=e.children[0].value;
obj['type']=e.children[0].type
return obj;
});
console.log(result);
If you want to be able to chose the children index:
const getDataChild = (a, i) => a.map(({id, children:ch}) => ({id, ...ch[i]}));
console.log(getDataChild(sample, 0)); // where 0 is the desired index
I have two arrays one is of keys and one is of its values
a=[name,place,job],
b=[John,Atlanta,Engineer]
I want to concat a and b and send it by post method like
xyz={
'name':'John',
'place:'Atlanta',
'job':'Engineer'
}
Working Demo
let a = ['name','place','job'];
let b = ['John','Atlanta','Engineer'];
let payload = a.reduce((obj, item, index) => (obj[item] = b[index], obj) ,{});
console.log(payload);
Service
this.http.post<any>(this.URL, payload);
You can iterate over an source array and then create a object with key and value then use Object.assign.
For ex:
a = ["name", "place", "job"];
b = ["John", "Atlanta", "Engineer"];
xyz = {};
constructor() {
this.a.forEach((item, index) => {
var obj = {
[this.a[index]]: this.b[index] || ""
};
Object.assign(this.xyz, obj);
});
console.log(this.xyz);
}
Working Demo
it is possible to use Object.assign and map methods:
let a = ['name','place','job'];
let b = ['John','Atlanta','Engineer'];
const result = Object.assign(...a.map((k, i) => ({[k]: b[i]})))
console.log(result);
I have the following string: Jack:13,Phil:15,Lucy:12I'm trying to fetch objects from this string.
This string would have 3 people objects with their ages. How can this be achieved?
I've tried the following:
var s = 'Jack:13,Phil:15,Lucy:12'
var obj1 = eval("("+s+")");
var obj2 = JSON.parse(s);
Logging any of the obj variables returns errors. Am I missing a simple trick here? Any explanation would be appreciated, thanks.
In general, if you're doing replaces on a string to turn it into something you can pass eval or JSON.parse, that's probably not your best approach. An in particular, avoid using eval (or its cousin new Function) when you can (you certainly can here), and always avoid eval (or its cousin new Function) with untrusted input.
A pair of splits with map does it:
const s = 'Jack:13,Phil:15,Lucy:12'
const people = s.split(",")
.map(e => e.split(":"))
.map(([name, age]) => ({name, age}));
console.log(people);
...or in ES5:
var s = 'Jack:13,Phil:15,Lucy:12'
var people = s.split(",")
.map(function(e) { return e.split(":"); })
.map(function(e) { return {name: e[0], age: e[1]}; });
console.log(people);
I'm not sure why I did two maps rather than just doing the second split and creating the object in the same callback; I guess I'm thinking more and more in a "functional programming" way. I'd change it, but Eddie's answer already does it in a single map, so...
...(edit) but since it looks like you wanted separate properties rather than using the person's name like Eddie did, here's an example of the above but with just a single map:
const s = 'Jack:13,Phil:15,Lucy:12'
const people = s.split(",")
.map(e => {
const [name, age] = e.split(":");
return {name, age};
});
console.log(people);
...or in ES5:
var s = 'Jack:13,Phil:15,Lucy:12'
var people = s.split(",")
.map(function(e) {
var parts = e.split(":");
return {name: parts[0], age: parts[1]};
});
console.log(people);
You can split() the string and use map() to loop thru the array. This will return an array of objects.
var s = 'Jack:13,Phil:15,Lucy:12';
var result = s.split(',').map(o => {
let [k, v] = o.split(':');
return {[k]: v};
});
console.log(result);
If you want a single object, you can use reduce
var s = 'Jack:13,Phil:15,Lucy:12';
var result = s.split(',').reduce((c, o) => {
let [k, v] = o.split(':');
return Object.assign(c, {[k]: v});
}, {});
console.log(result);
You can try with:
const result = s.split(',')
.map(value => value.split(':'))
.reduce((acc, [name, value]) => {
acc[name] = +value;
return acc;
}, {});
Output:
{
"Jack": 13,
"Phil": 15,
"Lucy": 12
}
As I'm sure you've worked out there are many ways to do this, I thought I'd add another method
let s = 'Jack:13,Phil:15,Lucy:12'
let obj = {};
s.split(",").forEach(part => {
obj[part.split(":")[0]] = part.split(":")[1];
})
console.log(obj);
This is a simple split the string and then on each item of the new array do a split and push the results into an empty object already declared.
You could split the parts and build a new object with key/value pairs.
var string = 'Jack:13,Phil:15,Lucy:12',
result = Object.assign(...string
.split(',')
.map(s => (([k, v]) => ({ [k]: v }))(s.split(':')))
);
console.log(result);
For getting an array with objects
var string = 'Jack:13,Phil:15,Lucy:12',
result = string
.split(',')
.map(s => (([name, age]) => ({ name, age }))(s.split(':')));
console.log(result);
Easy to do with .map():
var s = 'Jack:13,Phil:15,Lucy:12';
var items = s.split(',')
.map((entry) => entry.split(':'))
.map((item) => ({name: item[0], age: item[1]}));
console.log(items);