1

I am having to different arrays. For eg :

Array 1 is :

[536, 549]

Array 2 is :

[
    { text: "ABCD", value: 341 },
    { text: "WXYZ", value: 439 }
] 

I want to create an object as:

[
    {
        fieldId: 536,
        value: {
            value: 341,
            display_value: "ABCD"
        }
    },
    {
        fieldId: 549,
        value: {
            value: 439,
            display_value: "WXYZ"
        }
    }
]

I have no idea how to do this. Thanks in advance. :)

2
  • all you need is for loop and new array Commented Dec 16, 2017 at 13:48
  • @pwolaq can you tell me how ? Commented Dec 16, 2017 at 13:50

2 Answers 2

3
const arr_1 = [536, 549]
const arr_2 = [{text: "ABCD", value: 341},{text: "WXYZ", value: 439}]

// with map
let new_arr = arr_2.map( (ele, index) => {
  return {
    fieldID: arr_1[index],
    value: { value: ele.value, display_value: ele.text }
  };
});

// with for loop
let new_arr2 = [];
for(let i = 0; i < arr_2.length; i++){
  new_arr2.append({
    fieldID: arr_1[i],
    value: { value: arr_1[i].value, display_value: arr_1[i].text }
  });
}

Documentation for map(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Documentation for arrays: https://developer.mozilla.org/en-US/docs/Glossary/array

Documentation for objects: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object

Not sure if it is desired to have the numbers as string. You would have to use toString(). Also not sure if it should be a json string in the end, to get that use JSON.stringify()

Sign up to request clarification or add additional context in comments.

1 Comment

I am not getting the object as I desire.
0
const arr1 = [ 536, 549 ];
const arr2 = [
    { text: "ABCD", value: 341 },
    { text: "WXYZ", value: 439 }
];

const result = arr1.map((value, index) => ({
    fieldId: value,
    value: {
        display_value: arr2[index].text,
        value: arr2[index].value
    }
}));

Here, result will hold the desired value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.