I have a array as follows:
data = [
{
"attributes": {
"Name":"Material",
"Code":"ABC",
"Name":"Russia"
},
"AttributeList":{
"Attribute":[
{
"attributes":{
"AttributeName":"id",
"AttributeValue":"PROD"
}
},
{
"attributes":{
"AttributeName":"commodity",
"AttributeValue":"Rice"
}
},
{
"attributes":{
"AttributeName":"unit",
"AttributeValue":"1"
}
}
]
}
},
{
"attributes": {
"Name":"Material",
"Code":"CDF",
"Name":"INDIA"
},
"AttributeList":{
"Attribute":[
{
"attributes":{
"AttributeName":"id",
"AttributeValue":"PROD"
}
},
{
"attributes":{
"AttributeName":"commodity",
"AttributeValue":"Barley"
}
},
{
"attributes":{
"AttributeName":"unit",
"AttributeValue":"2"
}
}
]
}
},
{
"attributes": {
"Name":"Material",
"Code":"DEF",
"Name":"UK"
},
"AttributeList":{
"Attribute":[
{
"attributes":{
"AttributeName":"id",
"AttributeValue":"PC"
}
},
{
"attributes":{
"AttributeName":"commodity",
"AttributeValue":"PulSe"
}
},
{
"attributes":{
"AttributeName":"unit",
"AttributeValue":"3"
}
}
]
}
}
]
From this array I have to have a array if "AttributeName" is "id" and AttributeValue is "PROD" and "AttributeName" is "commodity" and AttributeValue is "Rice" or "Barley". then my final array will look like this:
finalArray = [
{
"code":"ABC",
"description":"Russia",
"unit":1
},
{
"code":"CDF",
"description":"INDIA",
"unit":2
}
]
code value will be value of "Code", description will be "Name" and unit value will come from AttributeList having Attribute name as Unit. How to do this?
CodePudding user response:
You can use Array.map()
combined with Array.find()
to achieve your goal.
I would use the JSON.parse()
method to not have to use square brackets, but if you don't want to do it, here's a code that might help:
let formatted = data.map((item, index, arr) => {
let attributes = item['attributes']
let unit = item['AttributeList']['Attribute'].find(obj => obj['attributes']['AttributeName'] === 'unit')['attributes']['AttributeValue'];
return {
"code": attributes['Code'],
"description": attributes['Name'],
"unit": unit
}
});
console.log(formatted);
- You have a syntax error, one of the objects is has a dot instead of a comma after it.
Hope it helps.
CodePudding user response:
Your object have duplicate key Name
"attributes": {
"Name":"Material",
"Code":"ABC",
"Name":"Russia"
},
Considering no duplicate key https://jsfiddle.net/aditya76/ar7q2knh/2/
let ans = [];
data.map(d => {
let isValidId = d.AttributeList.Attribute.some(x => x.attributes.AttributeName == "id" && x.attributes.AttributeValue == "PROD");
let isValidCommodity = d.AttributeList.Attribute.some(x => x.attributes.AttributeName== "commodity" && (x.attributes.AttributeValue == "Rice" || x.attributes.AttributeValue == "Barley"));
if(isValidCommodity && isValidId){
let code = d.attributes.Code;
let name = d.attributes.Name;
let unit = d.AttributeList.Attribute.find(x => x.attributes.AttributeName == 'unit');
ans.push({ "code" : code, "description" : name, "unit" : unit.attributes.AttributeValue });
}
});
console.log(ans);