javascript get key name from array of objects - javascript

from
"data":[{"ja":"大阪市"},{"en":"Osaka"}]
I want to get "ja" and "en".
I tried several ways...
data.map(function(_, i) { return i; });
it returns
array of numbers.
console.log(Object.keys(Object.values(data)));
all trials return
(2) [0, 1]
0: 0
1: 1
what can I do ??
please answer me. thank you.

Use map() and return the first key the object. You can get keys using Object.keys()
let data = [{"ja":"大阪市"},{"en":"Osaka"}]
let res = data.map(x => Object.keys(x)[0]);
console.log(res)
If you don't want to use [0] use flatMap()
let data = [{"ja":"大阪市"},{"en":"Osaka"}]
let res = data.flatMap(x => Object.keys(x));
console.log(res)
Note: The second method will also get the other properties other than first. For example
[{"ja":"大阪市","other":"value"},{"en":"Osaka"}] //["ja","other","en"];

let data = [{"ja":"大阪市"},{"en":"Osaka"}]
let res = data.reduce((arr, o) => {
return Object.keys(o).reduce((a, k) => {
if (a.indexOf(k) == -1) a.push(k);
return a;
}, arr)
}, []);
console.log(res);

Related

Create new JSON string from array

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)

How do construct ForEach into map in javascript

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

how I make object value as key of another object of array?

I'm getting data in form of array of objects like this...
let array = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
{serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];
I want this this array in this form please anyone help...
let arrayIWant = [
{
2:[{serviceId:2,name:'ahsan'},{serviceId:2,name:'john'}],
5:[{serviceId:5,name:'majeed'},{serviceId:5,name:'ziyad'}]
}
]
Please help
you can try like this to get your expected result
const array = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
{serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];
const iteratedArray = array.reduce((acc,val) => {
const key = val.serviceId;
if (!acc[key]) acc[key] = [];
acc[key].push(val);
return acc;
},{});
const arrayIWant = [iteratedArray];
console.log(arrayIWant);
Iterate through all the items in the array.
For each item:
If the serviceId does not exist as a prop of the object, set the prop's serviceId key with an array containing the item.
If it exists, add the item to that array.
As far as I understand you want to group the array of objects by the serviceId.
To do this you can either use groupBy method from lodash https://lodash.com/docs/#groupBy
or write your own implementation like this:
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
var data = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
{serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];
console.log(groupBy(data, 'serviceId'));
I hope that will help you.
You can use lodash library's _.keyBy method
_.keyBy(array, 'serviceId');
const _ = require('lodash')
let array = [{serviceId:2,name:'ahsan'}, {serviceId:5,name:'majeed'},
{serviceId:2,name:'john'}, {serviceId:5,name:'ziyad'}];
result = _.keyBy(array, 'serviceId');
console.log([result])
check this out. It should give you the desired result.

Converting a String to Multiple objects (javascript)

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);

Find index of any array using value in string array

a=[
{x:1,y:1,i:"Piechart1"},
{x:2,y:1,i:"Piechart2"},
{x:3,y:1,i:"Piechart3"}
]
str=["Piechart1","Piechart3"];
I want get index by comparing array string.Output in above example should be [0,2]
Could you please let me know how to achieve in lodash ,javascript
Use .map() to map the strings to their index, and .findIndex inside the .map() callback to locate the index of the object.
var a = [{x:1,y:1,i:"Piechart1"},{x:2,y:1,i:"Piechart2"},{x:3,y:1,i:"Piechart3"}];
var str = ["Piechart1","Piechart3"];
var res = str.map(s => a.findIndex(o => o.i == s));
console.log(res);
You can chain .filter(idx => idx != -1) on the end if there's any chance of one of the strings not being in the main array.
You can use reduce() method and includes() to check if element exists in another array.
const a = [{"x":1,"y":1,"i":"Piechart1"},{"x":2,"y":1,"i":"Piechart2"},{"x":3,"y":1,"i":"Piechart3"}]
const str = ["Piechart1", "Piechart3"];
const result = a.reduce((r, {i}, ind) => {
return str.includes(i) && r.push(ind), r
}, [])
console.log(result)
maps each value in str to their index in a.
str.map((str) => a.findIndex((ele) => str === ele.i))

Categories