how to change an array to json object in javascript - javascript

I have an array like below
let result = ["a","b","c","d"]
then need to change like below how to do it Thank you for any help.
result = [
{
type: "a",
image: "a.jpg"
},
{
type: "b",
image: "b.jpg"
},
{
type: "c",
image: "c.jpg"
},
{
type: "d",
image: "d.jpg"
}
]

I'd use map() for this.
const objResult = result.map((item) => {
return {
type: item,
image: item + '.jpg'
};
});

You can use array .map() method to return a new object with type & image properties like:
let result = ["a","b","c","d"]
result = result.map(r => ({type: r, image: `${r}.jpg`}))
console.log( result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can use Array.forEach() and Array.push() Array methods achieve the result:
let obj = [];
let result = ["a","b","c","d"]
result.forEach(function(el, i) {
obj.push({
type: el,
image: `${el}.jpg`
})
});
console.log(obj);

You would describe your function like this -
function convertResult(result){
let ans = [];
for(var i=0; i<result.length; i++){
ans[i] = {'type': result[i], 'image': result[i]+'.jpg'};
}
return ans;
}
then you would call your function as this -
let result = ["a","b","c","d"]
let ans = convertResult(result);

Use map
let result = ["a","b","c","d"]
const map = result.map(x => ({"type":x,"image": x+".jpg"}));
console.log(map);

Related

array of strings into array of objects with one attribute each?

How can I turn the below array
['12345', '83747']
into the below array of objects
[ {'id': '12345'}, {'id': '83747'} ]
using map?
My attempt so far, iDs is an empty array, chunk is an array of string.:
obj.iDs.concat(
chunk.map((item) => ({
id: item,
})),
);
An example, my IDE reports no issues with this code:
const body = [{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'},{'id':'1234'}]
const batchGetRequestObj = {
ids: [],
targetProperties: ['contentID, updateDateTime'],
};
function func() {
try {
chunkArray(
body.map((item) => {
return item.id;
}),
25,
).forEach((chunk) => {
batchGetRequestObj.ids.concat(
chunk.map((item) => ({
ids: item,
})),
);
console.log(batchGetRequestObj);
});
} catch (e) {
console.log(e);
}
}
function chunkArray(array: string[], size: number) {
const slicedArray = [];
for (let i = 0; i < array.length; i += size) {
slicedArray.push(array.slice(i, i + size));
}
return slicedArray;
}
Link to typescript playground
You're using concat, which doesn't mutate the arrays - you'll have to set the values back to the variable
var arr = ['12345', '83747']
var newids = obj.ids.concat(arr.map( str => { return {"id" : str}});
obj.ids = newids

how to get array according to conditions in javascript

My array comes like this
var data=[{PRODUCT : P1}, {PRODUCT: P2}]
I wantt to convert this into [P1, P2].
Sometimes my array comes like this
var data=[{ITEM: I1, QUANTITY:1}, {ITEM: I2, QUANTITY:2}]
I wantt to convert this into [I1, I2].
so can we make a common function, where I just want to extract particular value of array and make a new array.
p.s. Thank you in advance
I tried to write the logic like this:
data.map((d, index) => { var result= [];
result.includes(d[0]); })
but it,s not dynamic
You could define a function which will always get the first value of the first object key, this should satisfy your needs based on the above
var data1 = [{
ITEM: 'I1',
QUANTITY: 1
}, {
ITEM: 'I2',
QUANTITY: 2
}]
var data2 = [{
PRODUCT: 'P1'
}, {
PRODUCT: ' P2'
}]
function getArrayOfValues(list) {
return list.reduce((acc, x) => {
const firstValue = Object.values(x)[0];
acc.push(firstValue)
return acc;
}, [])
}
const result1 = getArrayOfValues(data1)
console.log(result1)
const result2 = getArrayOfValues(data2)
console.log(result2)
function getProductOrItem(list) {
return list.reduce((accumulator, obj) => {
if (obj.PRODUCT) {
accumulator.push(obj.PRODUCT);
} else if (obj.ITEM) {
accumulator.push(obj.ITEM);
}
return accumulator;
}, [])
}
you can iterate through your array with map() method and inside it extract the value of a first entity of an object in your array and simply get a new array with all values:
const data1 =[{PRODUCT : 'P1'}, {PRODUCT: 'P2'}]
const data2 = [{ITEM: 'I1', QUANTITY: 1}, {ITEM: 'I2', QUANTITY: 2 }]
const transformValuesOfArray = (arrayToTransform) =>
arrayToTransform.map(value => {
const firstObjectValue = Object.values(value)[0]
return firstObjectValue
})
console.log(transformValuesOfArray(data1))
console.log(transformValuesOfArray(data2))

Search and update array based on key

I have two array, need to update the second array by searching the position in the first array.
let arr1 = [{"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSITION":"GMH"}]
let arr2 = [{"EMAIL":"test1#stc.com","POSITION":"GM"},
{"EMAIL":"test2#stc.com","POSITION":"GMH"},
{"EMAIL":"test3#stc.com","POSITION":"RGM"},
{"EMAIL":"test3#CSR.COM.AU","POSITION":"GM"}]
Output Array
output = [ {"LEVEL":5,"EMAIL":"test1#stc.com","POSITION":"GM"},
{"LEVEL":5,"EMAIL":"test2#stc.com",""POSITION":"GMH"},
{"LEVEL":4,"EMAIL":"test3#stc.com","POSITION":"RGM"},
{"LEVEL":5,"EMAIL":"test3#CSR.COM.AU","POSITION":"GM"}]
I tried using the below code to filter but gives empty array, so not able to proceed further:
const output =arr1.filter((item) => {
return arr2.indexOf(item.POSITION) !== -1 && (item.POSITION)
});
I guess you can use map to create a new array. There you can use find to get the proper LEVEL property for the current POSITION.
One smart solution can be the following:
const positions = [{"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSITION":"GMH"}];
const emails = [{"EMAIL":"test1#stc.com","POSITION":"GM"},{"EMAIL":"test2#stc.com","POSITION":"GMH"},{"EMAIL":"test3#stc.com","POSITION":"RGM"},{"EMAIL":"test3#CSR.COM.AU","POSITION":"GM"}];
const result = emails.map(email => {
email['LEVEL'] = positions.find(p => p['POSITION'] === email['POSITION'])['LEVEL'];
return email;
})
console.log(result);
From Array.prototype.map() documentation:
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
From Array.prototype.find() documentation:
The find() method returns the value of the first element in the provided array that satisfies the provided testing function.
I hope this helps!
Another solution for beginners:
let arr1 = [{"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSITION":"GMH"}]
let arr2 = [{"EMAIL":"test1#stc.com","POSITION":"GM"},
{"EMAIL":"test2#stc.com","POSITION":"GMH"},
{"EMAIL":"test3#stc.com","POSITION":"RGM"},
{"EMAIL":"test3#CSR.COM.AU","POSITION":"GM"}]
function addLevel() {
const resultingArray = [];
arr2.forEach(itemarray2 => {
const copyOfArrayItem2 = Object.assign({}, itemarray2);
resultingArray.push(copyOfArrayItem2);
const itemArray1 = arr1.find(x => x.POSITION === itemarray2.POSITION);
if(itemArray1) {
copyOfArrayItem2.LEVEL = itemArray1.LEVEL;
}
});
return resultingArray;
}
const newArray = addLevel();
console.log(newArray);
You could take a Map and map new objects with LEVEL.
var array1 = [{ LEVEL: 4, POSITION: "RGM" }, { LEVEL: 5, POSITION: "GM" }, { LEVEL: 5, POSITION: "GMH" }],
array2 = [{ EMAIL: "test1#stc.com", POSITION: "GM" }, { EMAIL: "test2#stc.com", POSITION: "GMH" }, { EMAIL: "test3#stc.com", POSITION: "RGM" }, { EMAIL: "test3#CSR.COM.AU", POSITION: "GM" }],
levels = array1.reduce((m, { LEVEL, POSITION }) => m.set(POSITION, LEVEL), new Map),
result = array2.map(o => Object.assign({ LEVEL: levels.get(o.POSITION) }, o));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The simplest way is:
let arr1 = [{"LEVEL":4,"POSITION":"RGM"},{"LEVEL":5,"POSITION":"GM"},{"LEVEL":5,"POSITION":"GMH"}]
let arr2 = [{"EMAIL":"test1#stc.com","POSITION":"GM"},
{"EMAIL":"test2#stc.com","POSITION":"GMH"},
{"EMAIL":"test3#stc.com","POSITION":"RGM"},
{"EMAIL":"test3#CSR.COM.AU","POSITION":"GM"}]
let output = arr1.map(item => {
item.Email = arr2.find(a => {
return a.POSITION === item.POSITION
}).EMAIL;
return item;
});
console.log(output);

Refactor array of objects

The below code will have input as array of objects and I would like to convert into a different format.
The below code works fine but I need a more refactored shorter format of what I am trying to achieve.
var res = {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1#yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton#yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);
var res = [];
for(var key in parsedObj.data){
var emailObj = {};
var phoneObj = {}
if(parsedObj.data[key].email !== null){
emailObj.matchedRes = parsedObj.data[key].email;
emailObj.id = parsedObj.data[key].id;
emailObj.type = "email";
res.push(emailObj);
}
if(parsedObj.data[key].phone !== null){
phoneObj.matchedRes = parsedObj.data[key].phone;
phoneObj.id = parsedObj.data[key].id;
phoneObj.type="phone";
res.push(phoneObj);
}
}
console.log(res);
Desired output:
[ { matchedRes: 'jack1#yahoo.com', id: 'jack1', type: 'email' },
{ matchedRes: 'jack.clinton#yahoo.com', id: 'jack2', type: 'email' },
{ matchedRes: '+16464922600', id: 'jack2', type: 'phone' } ]
In the above code separate objects are created with phone and email for same id.
Here is a solution!
I just did a generic reducer, and then I use it on phone and email.
Then, I just spread the result of both calls to the result array :)
var res = {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1#yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton#yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);
const extractData = (obj, type) => obj.reduce((acc, elt) => (
elt[type] && acc.push({matchedRes: elt[type], id: elt.id, type: type})
, acc),[]);
const result = [...extractData(parsedObj.data, 'email'), ...extractData(parsedObj.data, 'phone')];
console.log(result);
Hope this helps, please do not hesitate to comment if you have any question ;)
You can use reduce with destructuring assignment . and check if email or phone is there than add a object accordingly
var res = {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1#yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton#yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);
let op = parsedObj.data.reduce((out,{id,email,phone})=>{
if(email){
out.push({matchedRes:email,id,type:`email`})
}
if(phone){
out.push({matchesRes:phone,id,type:`phone`})
}
return out
},[])
console.log(op)
If you want to see more use cases of You can destructuring assignment and it's uses you can check this one out
This should be possible with reduce:
var res = {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1#yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton#yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);
const keyFields = ["email", "phone"];
let result = parsedObj.data.reduce((acc, val) => {
keyFields.forEach(k => {
if (val[k]) acc.push({ matchedRes: val.email, id: val.id, type: k});
});
return acc;
}, []);
console.log("Result: ", result);
If you are looking for a little shorter code but still easy to read for anybody:
var res = {"matchObject":"{\"data\":[{\"id\":\"jack1\",\"firstname\":\"jack\",\"lastname\":\"hudson\",\"dob\":\"1990-01-01T00:00:00.000Z\",\"email\":\"jack1#yahoo.com\",\"phone\":null,\"orgid\":\"001\"},{\"id\":\"jack2\",\"firstname\":\"Jack\",\"lastname\":\"Clinton\",\"dob\":\"1991-01-01T00:00:00.000Z\",\"email\":\"jack.clinton#yahoo.com\",\"phone\":\"+16464922600\",\"orgid\":\"002\"}]}"};
var parsedObj = JSON.parse(res.matchObject);
var res = [];
Object.entries(parsedObj.data).forEach(el => {
el = el[1]
if(el.email !== null)
res.push({
matchedRes: el.email,
id: el.id,
type: "email"
})
if(el.phone !== null)
res.push({
matchedRes: el.phone,
id: el.id,
type: "phone"
})
})
console.log(res);

Modify object in Javascript

I'm trying to convert object
var data = {"USD": 12323,"CAD":32123}
to become
[{"id":"USD","value":12323},{"id":"CAD","value":32123}]
This is what i tried so far
var res = Object.keys(data).map(function(k) {
return [k, result[k]];
});
and get the result
[["USD", 12323],["CAD", 32123]]
Any help is very appreciated.
Thanks,
Just change your return statement to
return {id: k, value:result[k]}; //observe that an object is returned instead of an array
Demo
var data = {"USD": 12323,"CAD":32123};
var res = Object.keys(data).map(function(k) {
return {id: k, value:data[k]};
});
console.log( res );
You're creating one array, not an object. Change [] to {}:
var res = {"USD": 12323,"CAD":32123};
res = Object.keys(res).map(function(k) {
return {id: k, value:res[k]};
});
console.log(res);
as an alternative, you can use arrow function:
var res = {"USD": 12323,"CAD":32123};
res = Object.keys(res).map(x => x = { id: x, value: res[x]});
console.log(res);
or .every():
var res = {"USD": 12323,"CAD":32123};
var resWArrow = Object.entries(res).map(function(k) {
return {id: k[0], value: k[1]};
});
console.log('Without arrow: ' + JSON.stringify(resWArrow));
var resArrow = Object.entries(res).map(x => x = { id: x[0], value: x[1] });
console.log('With arrow: ' + JSON.stringify(resArrow));
With ES6, you could take Object.entries with Array#map and a destructuring assignment for the elements and short hand properties for the result.
var data = { "USD": 12323, "CAD": 32123 },
result = Object.entries(data).map(([id, value]) => ({ id, value }));
console.log(result);
You can iterate over the keys of the object and map them like follows:
Object.keys(res).map(function(key) {
return {id: key, value: data[key]};
}
Change the return statement and return an object
var res = {
"USD": 12323,
"CAD": 32123
}
var m = Object.keys(res).map(function(item) {
return {
id: item,
value: res[item]
}
})
console.log(m)

Categories

Resources