Javascript update Object attribute value - javascript

I´m trying to update the object atribute:
data : [
{"id":1,"rp":"2426","cr":"11-11"},
{"id":1,"rp":"1119","cr":"19-21"},
{"id":1,"rp":"3453","cr":"23-81"}
]
new object would be updated as below.
NewData: [
{"id":1,"rp":"2426","cr":"11/11"},
{"id":1,"rp":"1119","cr":"19/21"},
{"id":1,"rp":"3453","cr":"23/81"}
]
I looking to update the object cr atribute for all values, for example using javascript.replace() method, I would do replace("-","/").

That's just a simple usage of Array#map and String#replace:
ES2018
const data = [{"id":1,"rp":"2426","cr":"11-11"},{"id":1,"rp":"1119","cr":"19-21"},{"id":1,"rp":"3453","cr":"23-81"}]
const r = data.map(({ cr, ...rest }) => ({ cr: cr.replace('-', '/'), ...rest }));
console.log(r);

You could use map method to create new array and replace to update cr property.
var data = [{"id":1,"rp":"2426","cr":"11-11"},{"id":1,"rp":"1119","cr":"19-21"},{"id":1,"rp":"3453","cr":"23-81"}]
var update = data.map(({cr, ...rest}) => ({...rest, cr: cr.replace("-","/")}))
console.log(update)

You could iterate and map the array.
var data = [{ id: 1, rp: "2426", cr: "11-11" }, { id: 1, rp: "1119", cr: "19-21" }, { id: 1, rp: "3453", cr: "23-81" }],
newArray = data.map(o => Object.assign({}, o, { cr: o.cr.replace("-","/") }));
console.log(newArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can try this
let data = [
{"id":1,"rp":"2426","cr":"11-11"},
{"id":1,"rp":"1119","cr":"19-21"},
{"id":1,"rp":"3453","cr":"23-81"}
];
let newData = data.map(e=>{
e.cr = e.cr.replace(/-/, '/')
return e
})
console.log(newData)

Just try below
data.forEach(function(object){
object["cr"] = object["cr"].replace("-","/");
});

Try this:
const data = [
{"id":1,"rp":"2426","cr":"11-11"},
{"id":1,"rp":"1119","cr":"19-21"},
{"id":1,"rp":"3453","cr":"23-81"}
];
const newData = data.map(item => ({...item, cr: item.cr.replace(/-/g, '/')}));
console.log(newData);
If you need it to work in IE11:
const data = [
{"id":1,"rp":"2426","cr":"11-11"},
{"id":1,"rp":"1119","cr":"19-21"},
{"id":1,"rp":"3453","cr":"23-81"}
];
const newData = data.map(
function(item) {
return {
id: item.id,
rp: item.rp,
cr: item.cr.replace(/-/g, '/')
}
}
);
console.log(newData);

const data = [{"id":1,"rp":"2426","cr":"11-11"},{"id":1,"rp":"1119","cr":"19-21"},{"id":1,"rp":"3453","cr":"23-81"}]
const r = JSON.parse(JSON.stringify(data).replace(/-/g,'/'))
console.log(r);

Related

Convert array of objects to an object

I have created this function, however is not quite right. I get this response from it:
[
{
manufacturer: [
'AUDI'
]
},
{
body_colour: {
'BLACK'
}
}
]
However what I want is:
{
manufacturer: [
'AUDI'
],
body_colour: {
'BLACK'
}
}
How can I get to this? This is what I have at the moment:
checkForQueryString() {
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
let searchParams = Object.entries(params).map(([key, value]) => {
return {
[key]: value.split(',')
}
});
return searchParams;
},
Query String: ?manufacturer=AUDI&body_colour=BLACK
Use reduce not map
const params = {
manufacturer: "AUDI",
body_colour: "BLACK"
}
let searchParams = Object.entries(params).reduce((acc, [key, value]) => {
return {
...acc,
[key]: value.split(',')
}
}, {});
console.log(searchParams)
Object.fromEntries(urlSearchParams.entries()), Object.entries(params) are not necessary.
You can use a simple forEach function to achieve the desired result as from MDN DOCS.
function checkForQueryString() {
const searchParams = new URLSearchParams(window.location.search);
var result = {};
searchParams.forEach(function(value, key) {
result[key] = value.split(',');
});
return result;
}
console.log( checkForQueryString() );
When url is http:example.com?manufacturer=audi,tesla&body_colour=black,white
the output would be
{
"manufacturer": [
"audi",
"tesla"
],
"body_colour": [
"black",
"white"
]
}
Assumin you meant by your input:
body_colour: [
'BLACK'
]
The answer can be:
let myArray = [
{
manufacturer: ['AUDI']
},
{
body_colour: ['BLACK']
}
];
let newObj = Object.assign({}, ...myArray)
You can make use of Object.fromEntries with split and map:
const str = 'manufacturer=AUDI&body_colour=BLACK';
console.log(Object.fromEntries(str.split('&').map(o=>[o.split('=')[0],[o.split('=')[1]]])));

How can we compare two array of objects and display items from both array

I have two arrays like
const arr1=[{id:0,name:'aa',
userId:'22,23'},
{id:1,name:'bb',userId:'23'}]
const arr2=
[{id:22,username:'Peter'},
{id:23,username:'John'}]
arr1.map((val,k)=><div>
<p>val.userId</p>
</div>
I have getting output as
22,23
23
How to get an output like
Peter,John
John
You can use find() to get the username from arr2
const arr1 = [
{ id: 0, name: "aa", userId: "22,23" },
{ id: 1, name: "bb", userId: "23" },
];
const arr2 = [
{ id: 22, username: "Peter" },
{ id: 23, username: "John" },
];
const output = arr1.map(o =>
o.userId
.split(",")
.map(x => arr2.find(k => k.id === Number(x)).username)
.join(",")
);
output.map((val)=> <div><p>val</p></div>);
{arr1.map((val, k) => {
const ids = val.userId.split(",");
return ids.map((id) => {
const user = arr2.find((user) => user.id === Number(id));
return (
<div key={`${val.id}-${user.id}`}>
<p>{user.username}</p>
</div>
);
});
})}
Working Sandbox
You could with Array#reduce and Array#map
Array#reduce convert the array to object for easy to find. its better then using find with in map
Then Array#map update the new key of users.it will carry the username
const arr1=[{id:0,name:'aa', userId:'22,23'},{id:1,name:'bb',userId:'23'}]
const arr2= [{id:22,username:'Peter'}, {id:23,username:'John'}]
const obj = arr2.reduce((acc,{id,username})=>(acc[id]=username,acc),{})
const res = arr1.map(({userId,...a})=>{
const users = userId.split(',').map(id=> obj[id]).join(',')
return ({...a,userId,users})
})
console.log(res)
res.map((val,k)=><div>
<p>val.users</p>
</div>)

How to add duplicate key elements in JavaScript Object?

I want to make the following newArray using by following testArray.
newArray↓
let newArray = [
{section:"business",name:["Bob","John"]},
{section:"H&R",name:["Jen","Bobby"]},
]
testArray↓
let test = [
{section:"business",name:"Bob"},
{section:"business",name:"John"},
{section:"H&R",name:"Jen"},
{section:"H&R",name:"Bobby"},
]
First of all, I tried to find some key elements using by filter method like below.
let newArray = test.filter((x:any,i,self)=>
self.indexOf(x.section)===i
)
but this code output is [].
So, how do I make code to get my expected output?
Does anyone help me?
Use Array.reduce():
let test=[{section:"business",name:"Bob"},{section:"business",name:"John"},{section:"H&R",name:"Jen"},{section:"H&R",name:"Bobby"}];
let newArray = test.reduce((acc,cur) => {
if(acc.some(el => el.section === cur.section)){
acc.forEach((el,idx) => {
if(el.section === cur.section){
acc[idx].name.push(cur.name)
}
})
}else{
cur.name = [cur.name]
acc.push(cur)
}
return acc
},[])
console.log(newArray)
you can try this
const test = [{
section: "business",
name: "Bob"
},
{
section: "business",
name: "John"
},
{
section: "H&R",
name: "Jen"
},
{
section: "H&R",
name: "Bobby"
},
];
// gather sections
const sections = {};
test.forEach(t => {
sections[t.section] = sections[t.section] || [];
sections[t.section].push(t.name);
});
// convert sessions to array
const newArray = Object.keys(sections).map(k => {
return {
section: k,
name: sections[k]
};
});
console.log(newArray);

Mapping key and value to new keys in Javascript

Array of dictionaries should be converted simpler form.
data = [{A:1},{B:2},{C:3}]
data = {A: 1, B: 2}
data = ["0":{ A : 1, B : 2 , C : 3}]
Both are completely different datasets. I'm trying to map it also like below format.
The above should become like
data = [
{
name: "A",
y: 1
},
{
name: "B",
y: 2
},
{
name: "C",
y: 3
}
];
I tried this following approach but it's wrong
name = {}
data.forEach(function(k,x){
return name['name'] = k , name["y"] = x
})
Please suggest me a better approach.
map each object's entries to extract the key and the value, and return an object with name and y keys:
const data = [{A:1},{B:2},{C:3}]
const output = data.map(item => {
const [name, y] = Object.entries(item)[0];
return { name, y };
});
console.log(output);
If the keys (A, B, etc) are guaranteed to be unique throughout the array, then everything becomes simpler.
const data = [{A:1},{B:2},{C:3}];
const merged = Object.assign({}, ...data);
const newData = Object.entries(merged)
.map(([name, y]) => ({ name, y }));
console.log(newData);
However, if the keys aren't guaranteed unique, then refer to CertainPerformance's answer.
you can implement like this
var data = [{A:1},{B:2},{C:3}];
var reformattedArra = data.map(obj => {
let val = {};
val.name = Object.keys(obj)[0];
val.y = obj[Object.keys(obj)[0]];
return val;
})
console.log(JSON.stringify(reformattedArra));
I would say, use Object.keys() which is widly supported
let data = [{A:1},{B:2},{C:3}];
data = Object.assign({}, ...data);
data = Object.keys(data).map(key => ({ name: key, y: data[key] }));
console.log(data);
You yould could chekc the data format and if it is not an array, build one and reduce the array by taking the objetcs and create for each key/value a new object for the result set.
function simple(data) {
return (Array.isArray(data) ? data : [data]).reduce((r, o) => [...r, ...Object.entries(o).map(([name, y]) => ({ name, y }))], []);
}
console.log(simple([{ A: 1 }, { B: 2 }, { C: 3, D: 4 }]));
console.log(simple({ A: 1, B: 2 }));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Javascript concat and prefix or rename props

I have two arrays that I am concatinating.
However each of these arrays has same property name I want to leave by adding prefix to each.
Array A(aData) looks like
[
{
id: 1,
title: `title`
code: '34x'
},
...
]
Array B(bData) looke like:
[
{
id: 1
prop: 3,
otherporp: `prop`
code: 'hi67'
},
...
]
In order to combine the arrays I am doing concat and reduce to get only matching id's
const data: any = aData.concat(bData).reduce((acc, x) => {
acc[x.id] = Object.assign(acc[x.id] || {}, x);
return acc;
}, {});
return Object.values(data);
But the issue is that my bData code props getting lost.
Is there any way I can rename the code from aData to say aCode and the code from bData to bCode ?
You can create a new array from both of your array with updated key value aCode and bCode instead of code key. Then concat both of these arrays and merge them on the id key.
const arrA = [{ id: 1, title: `title`, code: '34x' }],
arrB = [{ id: 1, prop: 3, otherporp: `prop`, code: 'hi67'}];
const newArrA = arrA.map(({code, ...rest}) => ({...rest, aCode : code}));
const newArrB = arrB.map(({code, ...rest}) => ({...rest, bCode : code}))
const merged = Object.values([].concat(newArrA, newArrB).reduce((r,o) => {
r[o.id] = r[o.id] || Object.assign({},o);
Object.assign(r[o.id], o);
return r;
}, {}));
console.log(merged);
var arrA = [{
id: 1,
title: `title`,
code: '34x'
}],
arrB = [{
id: 1,
prop: 3,
otherporp: `prop`,
code: 'hi67'
}];
let newArrA = arrA.map(({
code,
...rest
}) => ({ ...rest,
aCode: code
}));
const newArrB = arrB.map(({
code,
...rest
}) => ({ ...rest,
bCode: code
}));
result = newArrA.map(function(v) {
var ret;
$.each(newArrB, function(k, v2) {
if (v2.id === v.id) {
ret = $.extend({}, v2, v);
return false;
}
});
return ret;
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories

Resources